CMSC 132: Object-Oriented Programming IIA Trick to Simplify List ImplementationDepartment of Computer ScienceUniversity of Maryland, College Park1Typical List ImplementationClass List {Node head;}Class Node {Object value;Node next;}2Insert in Front of i’th Elementvoid insertInFrontOf(int pos, Object value) {if (pos == 0) {Node newNode = new Node(value, head);head = newNode;} else {Node after = head;for(int i = 1; i < pos; i++) after = after.next;Node newNode = new Node(value, after.next);after.next = newNode;} }Cool List Implementation TrickYou must practice this technique if you expect to use ithead is never null, even for an empty listhead is set to first node when list is createdhead is never changedthe value of the first node isn’t ever looked atClass List {// value of first Node isn’t part of listfinal Node head = new Node(null);}Insert in Front of i’th Elementvoid insertInFrontOf(int pos, Object value) {Node after = head;for(int i = 0; i < pos; i++) after = after.next;Node newNode = new Node(value, after.next);after.next =
View Full Document