/* pre: Have object to be added to calling singly linked list object, and a link in the singly linked list AFTER * which the newItem's node must be added. * post: newItem is the element of the added node of the singly linked list. All other existing nodes of the * singly linked list retain their ordering relevant to the position of the newly added node. * The counter is modified to reflect the addition of a new node to the singly linked list. */ public void addAfter(Object newItem, Node link) { if (link == null) { this.addLast(newItem); return; } Node newNode = new Node(newItem); Node cur = head; Node prev = head; while (prev != link) { prev = cur; cur = cur.next(); } if (prev == cur) { newNode.setNext(cur.next()); cur.setNext(newNode); counter++; return; } prev.setNext(newNode); newNode.setNext(cur); counter++; }
/* pre: Have object to be added to calling singly linked list object, and a link in the singly linked list BEFORE * which the newItem's node must be added. * post: newItem is the element of the added node of the singly linked list. All other existing nodes of the * singly linked list retain their ordering relevant to the position of the newly added node. * The counter is modified to reflect the addition of a new node to the singly linked list. */ public void addBefore(Object newItem, Node link) { if (link == null) // list either empty or must be added at end of list { this.addLast(newItem); return; } Node newNode = new Node(newItem); Node cur = head; if (cur == link) // must be added as first node { this.addFirst(newItem); return; } while (cur.next() != link) cur = cur.next(); cur.setNext(newNode); newNode.setNext(link); counter++; }
/* pre: Have object to be added to calling singly linked list object, which may be empty. * post: newItem is the element of the FIRST node of the singly linked list. All other existing nodes of the * singly linked list retain their ordering AFTER the new first node. * The counter is modified to reflect the addition of a new node to the singly linked list. */ public void addFirst(Object newItem) { Node newNode = new Node(newItem); newNode.setNext(head); head = newNode; counter++; }