The following code snippet contains the Java code for the class ListNode used on a few exercises on my website.
public class ListNode {
private int val;
private ListNode next;
public ListNode() {
}
public ListNode(ListNode next) {
this.next = next;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public int val() {
return val;
}
public ListNode next() {
return this.next;
}
}
You will not need the method toString() but I leave its implementation here for completeness. This is used on the results section.
@Override
public String toString() {
String toString = "";
int count = 1;
ListNode currentNode = this;
while (currentNode != null) {
toString += "N" + count++ + (currentNode.next != null ? "," : "");
currentNode = currentNode.next;
}
return toString;
}
Linked list exercises test your knowledge on one the most commonly used data structures, and therefore you can expect such exercises on interviews for any programming language. Here is an easy exercise for a start: