Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly)
public void reverseList(){ Node before = null; Node tmp = head; Node next = tmp.next; while(tmp != null){ if(next == null) return; tmp.next = before; before = tmp; tmp = next; next = next.next; } }
And this is the Node class:
public class Node{ public int data; public Node next; public Node(int data, Node next){ this.data = data; this.next = next; } }
On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.
The recursive approach to reverse a linked list is simple, just we have to divide the linked lists in two parts and i.e first node and the rest of the linked list, and then call the recursion for the other part by maintaining the connection.
Reverse a LinkedList Using Recursive ApproachStep 1: Split the list given into two parts - the first node and the rest of the linked list. Step 2: Invoke the reverseList() method for the remaining portion of the linked list. Step 3: Join the rest to the first. Step 4: Fix the head pointer.
Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.
Node next = tmp.next; while(tmp != null){
So what happens when tmp == null?
You almost got it, though.
Node before = null; Node tmp = head; while (tmp != null) { Node next = tmp.next; tmp.next = before; before = tmp; tmp = next; } head = before;
Or in nicer (?) naming:
Node reversedPart = null; Node current = head; while (current != null) { Node next = current.next; current.next = reversedPart; reversedPart = current; current = next; } head = reversedPart;
ASCII art:
<__<__<__ __ : reversedPart : head (__)__ __ __ head : current: > > >
public Node<E> reverseList(Node<E> node) { if (node == null || node.next == null) { return node; } Node<E> currentNode = node; Node<E> previousNode = null; Node<E> nextNode = null; while (currentNode != null) { nextNode = currentNode.next; currentNode.next = previousNode; previousNode = currentNode; currentNode = nextNode; } return previousNode; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With