a linear linked list is a set of nodes. This is how a node is defined (to keep it easy we do not distinguish between node an list):
class Node{
Object data;
Node link;
public Node(Object pData, Node pLink){
this.data = pData;
this.link = pLink;
}
public String toString(){
if(this.link != null){
return this.data.toString() + this.link.toString();
}else{
return this.data.toString() ;
}
}
public void inc(){
this.data = new Integer((Integer)this.data + 1);
}
public void lappend(Node list){
Node child = this.link;
while(child != null){
child = child.link;
}
child.link = list;
}
public Node copy(){
if(this.link != null){
return new Node(new Integer((Integer)this.data), this.link.copy());
}else{
return new Node(new Integer((Integer)this.data), null);
}
}
public Node invert(){
Node child = this.link;
while(child != null){
child = child.link;
}
child.link = this;....
}
}
I am able to make a deep copy of the list. Now I want to invert the list so that the first node is the last and the last the first. The inverted list has to be a deep copy.
I started developing the invert function but I am not sure. Any Ideas?
Update: Maybe there is a recursive way since the linear linked list is a recursive data structure.
I would take the first element, iterate through the list until I get to a node that has no child and append the first element, I would repeat this for the second, third....
I sometimes ask this question in interviews...
I would not recommend using a recursive solution, or using a stack to solve this. There's no point in allocating O(n) memory for such a task.
Here's a simple O(1) solution (I didn't run it right now, so I apologize if it needs some correction).
Node reverse (Node current) {
Node prev = null;
while (current != null) {
Node nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev;
}
BTW: Does the lappend method works? It seems like it would always throw a NullReferenceException.
There's a great recursive solution to this problem based on the following observations:
The reverse of the empty list is the empty list.
The reverse of a singleton list is itself.
The reverse of a list of a node N followed by a list L is the reverse of the list L followed by the node N.
You can therefore implement the reverse function using pseudocode along these lines:
void reverseList(Node node) {
if (node == null) return; // Reverse of empty list is itself.
if (node.next == null) return; // Reverse of singleton list is itself.
reverseList(node.next); // Reverse the rest of the list
appendNodeToList(node, node.next); // Append the new value.
}
A naive implementation of this algorithm runs in O(n2), since each reversal requires an append, which requires an O(n) scan over the rest of the list. However, you can actually get this working in O(n) using a clever observation. Suppose that you have a linked list that looks like this:
n1 --> n2 --> [rest of the list]
If you reverse the list beginning at n2, then you end up with this setup:
n1 [reverse of rest of the list] --> n2
| ^
+------------------------------------------+
So you can append n1 to the reverse of the rest of the list by setting n1.next.next = n1, which changes n2, the new end of the reverse list, to point at n1:
[reverse of the rest of the list] --> n2 --> n1
And you're golden! Again more pseudocode:
void reverseList(Node node) {
if (node == null) return; // Reverse of empty list is itself.
if (node.next == null) return; // Reverse of singleton list is itself.
reverseList(node.next); // Reverse the rest of the list
node.next.next = node; // Append the new value.
}
EDIT: As Ran pointed out, this uses the call stack for its storage space and thus risks a stack overflow. If you want to use an explicit stack instead, you can do so like this:
void reverseList(Node node) {
/* Make a stack of the reverse of the nodes. */
Stack<Node> s = new Stack<Node>();
for (Node curr = node; node != null; node = node.next)
s.push(curr);
/* Start unwinding it. */
Node curr = null;
while (!s.empty()) {
Node top = s.pop();
/* If there is no node in the list yet, set it to the current node. */
if (curr == null)
curr = top;
/* Otherwise, have the current node point to this next node. */
else
curr.next = top;
/* Update the current pointer to be this new node. */
curr = top;
}
}
I believe that this similarly inverts the linked list elements.
I would treat the current list as a stack (here's my pseudo code):
Node x = copyOf(list.head);
x.link = null;
foreach(node in list){
Node temp = copyOf(list.head);
temp.link = x;
x = temp;
}
At the end x will be the head of the reversed list.
I more fammiliar whit C, but still let me try. ( I just do not sure if this runs in Java, but it should)
node n = (well first one)
node prev = NULL;
node t;
while(n != NULL)
{
t = n.next;
n.next = prev;
prev = n;
n = t;
}
Reversing a single-linked list is sort of a classic question. It's answered here as well (and well answered), it does not requires recursion nor extra memory, besides a register (or 2) for reference keeping.
However to the OP, I guess it's a school project/homework and some piece of advice, if you ever get to use single linked list for some real data storage, consider using a tail node as well. (as of now single linked lists are almost extinct, HashMap buckets comes to mind, though).
Unless you have to check all the nodes for some condition during 'add', tail is quite an improvement. Below there is some code that features the reverse method and a tail node.
package t1;
public class SList {
Node head = new Node();
Node tail = head;
private static class Node{
Node link;
int data;
}
void add(int i){
Node n = new Node();
n.data = i;
tail = tail.link =n;
}
void reverse(){
tail = head;
head = reverse(head);
tail.link = null;//former head still links back, so clear it
}
private static Node reverse(Node head){
for (Node n=head.link, link; n!=null; n=link){//essentially replace head w/ the next and relink
link = n.link;
n.link = head;
head = n;
}
return head;
}
void print(){
for (Node n=head; n!=null;n=n.link){
System.out.println(n.data);
}
}
public static void main(String[] args) {
SList l = new SList();
l.add(1);l.add(2);l.add(3);l.add(4);
l.print();
System.out.println("==");
l.reverse();
l.print();
}
}
I was wondering something like that(I didnt test it, so):
invert(){
m(firstNode, null);
}
m(Node v, Node bef){
if(v.link != null)
m(v.link,v);
else
v.link=bef;
}
Without much testing,
Node head = this;
Node middle = null;
Node trail = null;
while (head != null) {
trail = middle;
middle = head;
head = head.link;
middle.link = trail;
}
head = middle;
return head;
public ListNode Reverse(ListNode list)
{
if (list == null) return null;
if (list.next == null) return list;
ListNode secondElem = list.next;
ListNode reverseRest = Reverse(secondElem);
secondElem.Next = list;
return reverseRest;
}
Hope this helps.
Related
outputI'm doing a project for class where I have to sort a linked list using insertion sort. I am supposed to take user input, convert it into an int array and insert it into a linked list. My problem is for some reason when I go to print the linked list post sort, it only prints the first node. The code worked jsut fine when I was initially testing it(I was manually entering what integers to insert), but now that I'm using arrays it doesn't seem to work. Can anyone help?
(this is only one class from my project but let me know if more information is needed).
Edit: I added a picture of what my output lokos like
import java.util.Arrays;
public class SortLL {
static LL top;
static Node head;
static Node sorted;
//function to insert node at head
public void toHead(int newData){
Node newNode = new Node(newData);
newNode.link = head;
head = newNode;
}
public static void insertion(Node ref){ //problem right now is that i'm only passing in one node
sorted = null;
Node current = ref;
while(current != null){
Node next = current.link;
sortInsert(current);
current = next;
}
head = sorted;
}
static void sortInsert(Node newNode){ //item in this case is val
if(sorted == null || sorted.item >= newNode.item){
newNode.link = sorted;
sorted = newNode;
} else {
Node current = sorted;
while(current.link != null && current.link.item < current.item){
current = current.link;
}
newNode.link = current.link;
current.link = newNode;
}
}
void printList(Node head)
{
while (head != null)
{
System.out.print(head.item + " ");
head = head.link;
}
}
public static void sortList(int[] arrA, int[] arrB){
int[] arr = new int[arrA.length + arrB.length];
System.arraycopy(arrA, 0, arr, 0, arrA.length);
System.arraycopy(arrB, 0, arr, arrA.length, arrB.length);
System.out.println("checking array " + Arrays.toString(arr));
SortLL sort = new SortLL();
for(int i=0;i<arr.length;i++){
sort.toHead(arr[i]);
}
System.out.println("sortLL.java\n\n");
sort.printList(sort.head);
sort.sortInsert(sort.head);
System.out.println("\nLinkedList After sorting");
sort.printList(sort.head);
}
}
Inside your printList() method, you shift the head variable while iterating over the list. When you move the head variable to the end, you essentially destroy the linked list since you lose your reference to the beginning of it. Java will then automatically treat the unreferenced nodes as garbage.
From what I see, after you first call sort.printList(sort.head), you destroyed your original linked list, so it didn't work when sorting.
When calling printList(), it might help to use a temporary node (Node temp = head) so that you don't lose your original head variable.
I am trying to delete a node in the middle of two other nodes in a singly linked list.
public void deleteAfter(Node del){
del.next=del.next.next;
}
where it deletes the the node that is after the specified node,del.
I get a null pointer exception .I think the problem is after deletion the link with other nodes is broken.How can I mend it .Here's my full code :
public class Node{
public Object item;
public Node next;
public Node(){
item=null;
next=null;
}
public Node(Object x){
item=x;
next=null;
}
public void insertAfter(Node after,Object x){
Node newNode=new Node(x);
newNode.next=after.next;
after.next=newNode;
}
public void deleteAfter(Node del){//Deletes the node that is after the specified node
del.next=del.next.next;
}
public static void main (String args[]){
Node front=new Node(),p=new Node(),q=new Node();
p.item="green";
q.item="red";
p.next=q;
front=p;
front.deleteAfter(p);
front.insertAfter(p,"black");
front.insertAfter(q,"blue");
front.insertAfter(q.next,"orange");
front.deleteAfter(q);
System.out.println(front.item);
System.out.println(front.next.item);
System.out.println(front.next.next.item);
System.out.println(front.next.next.next.item);
}
}
First your list should remember last element or head.
public class YourList{
Node heaed;
public YourList(){
head = null;
}
public void insert(Node node){
if(last == null){
head = node;
}
}
public void deleteAfter(Node del){
if(del.next == head)){
head = del;
}
if(del.next == null){
//do nothing because there is nothing to delete
}
else{
del.next=del.next.next;
}
}
}
At:
p.next=q;
front=p;
front.deleteAfter(p);
front.insertAfter(p,"black");
You have created a two node linked list starting at p, and pointed front to it, then you shrank it down to a one node linked list, and bumped it back to two, consisting of { "green", "black" }. q is a singleton list node which you later manipulate.
When you print starting from front, since it only has two nodes, trying to obtain the item of the third node, which doesn't exist, causes your exception.
Your question started out by asking if there was something wrong with your deleteAfter(), and there is in that it won't correctly handle any correct list of nodes, only a list that actually has something after it. Passing in an empty list or a list with only one node in it will result in an exception.
You can first find the middle node using two pointer approach and then delete the node.
public Node findMiddleNode(Node node){
Node runner = node;
while(node!=null){
node = node.next;
if(node != null){
node = node.next;
runner = runner.next;
}
}
return runner;
}
public static boolean deleteNode(Node node){
if(node==null || node.next==null) return false;
Node next = node.next;
node.data = next.data;
node.next = next.next;
return true;
}
Solution which first calculates the size of the list and deletes the n/2 element without using two pointers.
For example, if given linked list is 1->2->3->4->5 then linked list should be modified to 1->2->4->5. If there are even nodes, then there would be two middle nodes, the second middle element gets deleted. For example, if given linked list is 1->2->3->4->5->6 then it should be modified to 1->2->3->5->6.
public void deleteMiddle() {
if (head == null) {
System.out.println("List is emplty");
return;
} else if (head.next == null) {
head = null;
return;
} else {
int count = 0;
int nodeDeleteIndex = 0;
Node node = this.head;
Node temp = this.head;
// To calculate the list size
while (node != null) {
count++;
node = node.next;
}
// getting the n/2 index of the node which needs to be deleted
nodeDeleteIndex = (count / 2);
for (int i = 0; i < nodeDeleteIndex - 1; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
}
}
Excuse my ignorance but I am beginning to prepare for my first technical interview and came across this question and answer on the topic linkedlist
Question: Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node
public static boolean deleteNode(LinkedListNode n) {
if (n == null || n.next == null) {
return false; // Failure
}
LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
I want to start playing with this code (making changes compile test) but I'm not sure how to start doing this in Java. I cannot find the LinkedListNode class in Java docs.
This might be a very silly question but if someone can point me in the right direction - will appreciate it.
EDIT
Thanks for the quick and useful responses. I guess my question was not very clear. The algorithm above was provided as a solution to that question. I wanted to know how to implement that in Java so I can play around with the code.
thanks
The code will only work properly if there's a tail node on the list.
The algorithm works with the following logic
When referring to the node to be deleted, call it "curr"
When referring to the node before "curr", call it "prev"
When referring to the node after "curr", call it "next"
To effectively delete our node, "prev".next should point to "next"
It currently points to "curr"
Our problem is that we have no reference to "prev"
We know "prev".next points to "curr"
Since we cannot change the fact that "prev".next points to "curr",
we must have "curr" gobble up "next"
We make "curr"s data be "next"s data
We make "curr"s next be "next"s next
The reason this only works if there's a tail guard
is so we can make "next" be the "tail" node of the
list. (Its data is null and it's next is null.) Otherwise,
"prev".next would still be pointing to something.
Here's a class that uses LinkedListNode. I should note that if you're applying for a position as a programmer, you should be able to do this basically from memory. :-)
class LinkedList<E> {
static class LinkedListNode<E> {
E data;
LinkedListNode<E> next;
}
/**
* Not exactly the best object orientation, but we'll manage
*/
static <E> E deleteNode(LinkedListNode<E> node) {
if(node == null || node.next == null) return null;
E retval = node.data;
LinkedListNode<E> next = node.next;
node.data = next.data;
node.next = next.next;
return retval;
}
private LinkedListNode<E> head;
private LinkedListNode<E> tail;
public LinkedList() {
this.head = new LinkedListNode<E>();
this.tail = new LinkedListNode<E>();
head.next = tail;
}
public void addLast(E e) {
LinkedListNode<E> node = new LinkedListNode<E>(); // e and next are null
tail.data = e;
tail.next = node;
tail = node;
}
public void addFirst(E e) {
LinkedListNode<E> node = new LinkedListNode<E>(); // e and next are null;
node.next = head.next;
node.data = e;
head.next = node;
}
public E deleteFirst() {
LinkedListNode<E> first = head.next;
head.next = first.next;
return first.data;
}
public E deleteLast() {
// cannot do without iteration of the list! :-(
throw new UnsupportedOperationException();
}
public LinkedListNode<E> findFirst(E e) {
LinkedListNode<E> curr = head.next;
while(curr != null) {
if(curr.data != null && curr.data.equals(e)) return curr;
curr = curr.next;
}
return null;
}
public void print() {
LinkedListNode<E> curr = head.next;
while(curr.next != null) {
System.out.println(curr.data);
curr = curr.next;
}
}
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addLast("Apple");
list.addLast("Bear");
list.addLast("Chair");
list.addLast("Dirt");
//list.print();
LinkedListNode<String> bear = list.findFirst("Bear");
deleteNode(bear);
list.print();
}
}
This class is most likely a hypothetical class used for this Linked List example question.
LinkedListNode is a class that you will define to hold data. To get your above example to work - I've quickly written this code (just to make you understand the simple concept) in which I am creating 3 nodes (which are linked to each other) and then deleting the middle one calling the deleteNode method that you have specified in your question.
The code is pretty self explanatory. Let me know if this helps.
Good Luck
class LinkedListNode
{
public Object data;
public LinkedListNode next;
public LinkedListNode(Object data) {
this.data = data;
}
}
class DeleteNodeLinkedList
{
public static void main(String[] args)
{
LinkedListNode node_1 = new LinkedListNode("first");
LinkedListNode node_2 = new LinkedListNode("second");
node_1.next = node_2;
LinkedListNode node_3 = new LinkedListNode("third");
node_2.next = node_3;
System.out.println("*** Print contents of linked list");
LinkedListNode current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println("*** Now delete second node");
deleteNode(node_2);
System.out.println("*** Print after deleting second node");
current = node_1;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
public static boolean deleteNode(LinkedListNode n)
{
if (n == null || n.next == null) {
return false; // Failure
}
LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
}
The important details in this question pertain to data structures, java is just the language that is being used to implement in this case.
You should read the wikipedia article about linked lists, and for this question be careful that your solution doesn't produce any dangling references or orphan nodes.
Do some searches on the two terms in bold, and make sure that you understand them
Your question is bit confusing. whether you want a logic to remove a node in a singly linkedlist or you want to learn and use java LinkedlistNode.
if you are in second the following link will help you
LinkedListNodee
or if you want the logic
let P the pointer to the current node
P->data = P->next->data
Q=P->next
P->next=Q->next
delete(Q)
I am confused as to how to add to the front of the linked list.
/**
* data is added to the front of the list
* #modifies this
* #ffects 2-->4-->6 becomes data-->2-->4-->6
*/
public void insert(E data) {
if (front == null)
front = new Node(data, null);
else {
Node temp = new Node(data, front);
front = temp;
}
}
This creates a cycle. How do I avoid that?
I have a LinkedList class which holds the front Node, in a variable called front.
I have a Node class within this LinkedList class.
Any help would be appreciated.
Thank you.
Don't you have access to "Next" node ?
In that case
public void insert(E data) {
if (front == null) {
front = new Node(data, null);
} else {
Node temp = new Node(data, null);
temp.next = front;
front = temp;
}
}
--
class LinkedList {
Node front;
LinkedList() {
front = null;
}
public void AddToFront(String v) {
if (front == null) {
front = new Node(v);
} else {
Node n = new Node(v);
n.next = front;
front = n;
}
}
}
class Node {
public Node next;
private String _val;
public Node(String val) {
_val = val;
}
}
I'm assuming that the Node constructor takes a next pointer as its 2nd argument, in which case I don't see anything obvious wrong with this code. This really sounds like a homework question. If it is, you should tag it as such.
With my limited linked list knowledge, I would venture this:
Node temp = new Node(data);
temp.next = front;
front = temp;
You might want to wait around for somebody to confirm though.
This creates a cycle. How do I avoid that?
It is not possible to know for sure without the rest of the code for your linked list implementation, but the code that you have supplied doesn't look like it creates a cycle at all.
If a cycle is being created, it is most likely being created elsewhere. Alternatively, you / your tests are misdiagnosing some other failure as being caused by a cycle.
If you need more help, post more code / evidence ... particularly the Node constructor, and the code that makes you think you have a cycle.
Add a new node and if the current head is not null, then point the current head to the newly created node as the next node.
Node insert(Node head,int x) {
Node node = new Node();
node.data = x;
if(head != null) {
node.next = head;}
return node;
}
This is my Implementation of Inserting a node to front or head of the Linked List in Java.
void insertAtHead(Object data){
if(head==null) {
head = new Node(data);
}
Node tempNode = new Node(data);
Node currentNode = head;
tempNode.setNext(currentNode.getNext());
head.setNext(tempNode);
incrementCounter();
}
A simple and quick [ may not be efficient ] solution is to create a temporary new LinkedList with the new element and merge the two lists together with the temp-list in the front.
see the example below
import java.util.*;
public class Main
{
public static Queue<Integer> addFirst(Queue<Integer> intQueue, Integer i){
Queue<Integer> intQueue2 = new LinkedList<Integer>();
intQueue2.add(i);
intQueue2.addAll(intQueue);
intQueue = intQueue2;
return intQueue;
}
public static void main(String[] args) {
System.out.println("Hello LinkedList");
Queue<Integer> intQueue = new LinkedList<Integer>();
intQueue.add(3);
intQueue.add(4);
intQueue.add(5);
intQueue = addFirst(intQueue,2);
intQueue = addFirst(intQueue,1);
System.out.println(intQueue);
}
}
I am implementing my own linked list in Java. The node class merely has a string field called "name" and a node called "link". Right now I have a test driver class that only inserts several names sequentially. Now, I am trying to write a sorting method to order the nodes alphabetically, but am having a bit of trouble with it. I found this pseudocode of a bubblesort from someone else's post and tried to implement it, but it doesn't fully sort the entries. I'm not really quite sure why. Any suggestions are appreciated!
private void sort()
{
//Enter loop only if there are elements in list
boolean swapped = (head != null);
// Only continue loop if a swap is made
while (swapped)
{
swapped = false;
// Maintain pointers
Node curr = head;
Node next = curr.link;
Node prev = null;
// Cannot swap last element with its next
while (next != null)
{
// swap if items in wrong order
if (curr.name.compareTo(next.name) < 0)
{
// notify loop to do one more pass
swapped = true;
// swap elements (swapping head in special case
if (curr == head)
{
head = next;
Node temp = next.link;
next.link = curr;
curr.link = temp;
curr = head;
}
else
{
prev.link = curr.link;
curr.link = next.link;
next.link = curr;
curr = next;
}
}
// move to next element
prev = curr;
curr = curr.link;
next = curr.link;
}
}
}
I spent some minutes eyeballing your code for errors but found none.
I'd say until someone smarter or more hard working comes along you should try debugging this on your own. If you have an IDE like Eclipse you can single-step through the code while watching the variables' values; if not, you can insert print statements in a few places and hand-check what you see with what you expected.
UPDATE I
I copied your code and tested it. Apart from the fact that it sorts in descending order (which may not be what you intended) it worked perfectly for a sample of 0, 1 and 10 random nodes. So where's the problem?
UPDATE II
Still guessing what could be meant by "it doesn't fully sort the entries." It's possible that you're expecting lexicographic sorting (i.e. 'a' before 'B'), and that's not coming out as planned for words with mixed upper/lower case. The solution in this case is to use the String method compareToIgnoreCase(String str).
This may not be the solution you're looking for, but it's nice and simple. Maybe you're lazy like I am.
Since your nodes contain only a single item of data, you don't really need to re-shuffle your nodes; you could simply exchange the values on the nodes while leaving the list's structure itself undisturbed.
That way, you're free to implement Bubble Sort quite simply.
you should use the sorting procedures supplied by the language.
try this tutorial.
Basically, you need your element class to implement java.lang.Comparable, in which you will just delegate to obj.name.compareTo(other.name)
you can then use Collections.sort(yourCollection)
alternatively you can create a java.util.Comparator that knows how to compare your objects
To obtain good performance you can use Merge Sort.
Its time complexity is O(n*log(n)) and can be implemented without memory overhead for lists.
Bubble sort is not good sorting approach. You can read the What is a bubble sort good for? for details.
This may be a little too late. I would build the list by inserting everything in order to begin with because sorting a linked list is not fun.
I'm positive your teacher or professor doesn't want you using java's native library. However that being said, there is no real fast way to resort this list.
You could read all the nodes in the order that they are in and store them into an array. Sort the array and then relink the nodes back up. I think the Big-Oh complexity of this would be O(n^2) so in reality a bubble sort with a linked list is sufficient
I have done merge sort on the singly linked list and below is the code.
public class SortLinkedList {
public static Node sortLinkedList(Node node) {
if (node == null || node.next == null) {
return node;
}
Node fast = node;
Node mid = node;
Node midPrev = node;
while (fast != null && fast.next != null) {
fast = fast.next.next;
midPrev = mid;
mid = mid.next;
}
midPrev.next = null;
Node node1 = sortLinkedList(node);
Node node2 = sortLinkedList(mid);
Node result = mergeTwoSortedLinkedLists(node1, node2);
return result;
}
public static Node mergeTwoSortedLinkedLists(Node node1, Node node2) {
if (null == node1 && node2 != null) {
return node2;
} else if (null == node2 && node1 != null) {
return node1;
} else if (null == node1 && null == node2) {
return null;
} else {
Node result = node1.data <= node2.data ? node1 : node2;
Node prev1 = null;
while (node1 != null && node2 != null) {
if (node1.data <= node2.data) {
prev1 = node1;
node1 = node1.next;
} else {
Node next2 = node2.next;
node2.next = node1;
if (prev1 != null) {
prev1.next = node2;
}
node1 = node2;
node2 = next2;
}
}
if (node1 == null && node2 != null) {
prev1.next = node2;
}
return result;
}
}
public static void traverseNode(Node node) {
while (node != null) {
System.out.print(node + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
MyLinkedList ll1 = new MyLinkedList();
ll1.insertAtEnd(10);
ll1.insertAtEnd(2);
ll1.insertAtEnd(20);
ll1.insertAtEnd(4);
ll1.insertAtEnd(9);
ll1.insertAtEnd(7);
ll1.insertAtEnd(15);
ll1.insertAtEnd(-3);
System.out.print("list: ");
ll1.traverse();
System.out.println();
traverseNode(sortLinkedList(ll1.start));
}
}
The Node class:
public class Node {
int data;
Node next;
public Node() {
data = 0;
next = null;
}
public Node(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public Node getNext() {
return this.next;
}
public void setData(int data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
#Override
public String toString() {
return "[ " + data + " ]";
}
}
The MyLinkedList class:
public class MyLinkedList {
Node start;
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (start == null) {
start = newNode;
return;
}
Node traverse = start;
while (traverse.getNext() != null) {
traverse = traverse.getNext();
}
traverse.setNext(newNode);
}
public void traverse() {
if (start == null)
System.out.println("List is empty");
else {
Node tempNode = start;
do {
System.out.print(tempNode.getData() + " ");
tempNode = tempNode.getNext();
} while (tempNode != null);
System.out.println();
}
}
}