Linked List fundamental concepts [closed]
-
05-11-2019 - |
Question
I am trying to understand the basics of Linked List. The definition of my LinkedList class is as follows:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
Now I am facing a problem. My code is as follows:
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode slow = head;
head.next = null;
prev.next = slow;
ListNode temp = slow.next;
prev.next = temp;
System.out.println(dummy.next); //comes out null
Why is it coming out as null? dummy.next was pointing to head and I only changed slow and prev?
Can we use slow and head interchangeably? If yes, then why does this happen?
// head points to a Linked list starting from 1 in 1 -> 2 -> 3
ListNode curr = head;
while(curr.next!= null){
curr= curr.next;
}
System.out.println(curr);
System.out.println(head); //these are different and head does not change
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with cs.stackexchange