I was reading about linked lists in java , I did program this code , when I run it I get 3 as output , it should print out a reverse order of the inserted numbers as following : 10 7 3 .. what is wrong with my code?
public class List { private class ListNode { private int contents; private ListNode next; ListNode(int contents) { this.contents = contents; this.next = null; } } private ListNode head; public List() { head = null; } public void insert(int contents) { ListNode newNode = new ListNode(contents); if (head == null) { head = newNode; } ListNode current = head; while (current != null) { current = current.next; } current = newNode; } public void reverse() { ListNode current = head; ListNode nodeNext = current.next; while (nodeNext != null) { current.next = null; nodeNext.next = current; current = nodeNext; } head = current; } public String toString() { String s = ""; ListNode current = head; while (current != null) { s = current.contents + s; current = current.next; } return s; } public static void main(String[] args) { List l = new List(); l.insert(3); l.insert(7); l.insert(10); l.reverse(); System.out.println(l.toString()); } } Thanks
nextwhen inserting value. Using a debugger, you would have quickly found that.public void insert(int contents, ListNode next) {System.out.println(l.reverse());in the main method eclipse says :The method println(boolean) in the type PrintStream is not applicable for the arguments (void)