In: Computer Science
//LinkNode is a class for storing a single node of a linked list storing integer values. It has two public data fields for the data and the link to
//the next node in the list and has three constructors:
public class LinkNode {
public int data;
public LinkNode next;
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public LinkNode (int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public LinkNode (int data, LinkNode next) {
this.data = data;
this.next = next;
}
}
Assume:
LinkNode list = new LinkNode( );
a.
+----+----+ +----+----+
list ----> | 1 | +----> | 2 | / |
+----+----+ +----+----+
List.next = new LinkNode(9);
Draw your diagram here…
b.
+----+----+ +----+----+
list ----> | 1 | +----> | 2 | / |
+----+----+ +----+----+
List.next = new LinkNode(9, list.next);
Draw your diagram here…
c.
+----+----+ +----+----+ +----+----+
list ----> | 7 | +----> | 8 | +----> | 3 | / |
+----+----+ +----+----+ +----+----+
List = new LinkNode(5, list.next.next);
Draw your diagram here…
a) Ans:
Here we have list pointing to 1 initally. List.next is changed to a new node with data 9, hence the new linked node diagram would be:
+----+----+ +----+----+
list ----> | 1 | +----> | 9 | / |
+----+----+ +----+----+
===================================
b) Ans:
new LinkNode(9, list.next); ==> this will create a node with value 9 and next pointing to node with data 2 of list.
Now List.next is set to above value. Hence new list would be
+----+----+ +----+----+ +----+----+
list ----> | 1 | +----> | 9 | +----> | 2 | / |
+----+----+ +----+----+ +----+----+
=================================
c) Ans
List = new LinkNode(5, list.next.next);
A new link node with value 5 is created. The next value is set to node pointing at 3 of the orignal list. Hence new list would be
+----+----+ +----+----+
list ----> | 5 | +----> | 3 | / |
+----+----+ +----+----+
==========
For any query comment.