I am trying to flip a linked list iteratively using a stack. I determined where the problem is, but for the life of me, I can’t understand why the code does not iterate correctly when I call the following ListNode method. I noted in the code below where the error occurs.
This is the result when I run the code:
Before: 1->2->3->4->null
After: 4->3->3->4->null
Here's what you should get:
Before: 1->2->3->4->null
After: 4->3->2->1->null
Can someone point me in the right direction regarding what is happening? Thank!
Here is the code:
public class Solution {
public static void main(String[] args) {
private static Solution soln = new Solution();
ListNode head = makeLinkedList(4);
System.out.print("Before: ");
printLinkedList(head);
System.out.println();
soln.reverseList(head);
System.out.print(" After: ");
printLinkedList(head);
System.exit(0);
}
public ListNode reverseList(ListNode head) {
Stack<ListNode> listContents = new Stack<ListNode>();
ListNode tmp = head;
while (tmp != null) {
listContents.push(tmp);
tmp = tmp.next;
}
tmp = head;
while (tmp != null) {
tmp.val = listContents.pop().val;
tmp = tmp.next;
}
return head;
}
}
How is a ListNode defined:
public class ListNode {
int val;
ListNode next = null;
public ListNode(int item) {
val = item;
}
}
This is how I create a linked list:
private static ListNode makeLinkedList(int numNodes) {
ListNode head = null;
ListNode tmp = null;
for (int i = 1; i < numNodes + 1; i++) {
if (tmp == null) {
tmp = new ListNode(i);
head = tmp;
} else {
tmp.next = new ListNode(i);
tmp = tmp.next;
}
}
return head;
}
Helper Method:
private static void printLinkedList(ListNode head) {
ListNode tmp = head;
while (tmp != null) {
System.out.print(tmp.val + "->");
tmp = tmp.next;
}
System.out.print("null");
}
source
share