Skip to content

Instantly share code, notes, and snippets.

@chouclee
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chouclee/9b6beccbba1579ac0247 to your computer and use it in GitHub Desktop.
Save chouclee/9b6beccbba1579ac0247 to your computer and use it in GitHub Desktop.
[CC150][2.3] Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. EXAMPLE Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
public class LinkedList<Item> {
private Node<Item> first;
private Node<Item> last;
private int N;
public LinkedList() {
this.N = 0;
}
public void add(Node<Item> node) {
if(node == null) return;
if (N == 0) {
first = node;
last = first;
N++;
}
else {
Node<Item> oldLast = last;
last = node;
oldLast.next = last;
}
}
//* copy node.next to node, and free node.next
//* complexity : O(1)
//* warning: it doesn't delete the REAL node
public void delete(Node<Item> node) {
if(node == null) return;
if (node == first || node == last)
throw new UnsupportedOperationException();
node.item = node.next.item;
node.next.item = null;
node.next = node.next.next;
N--;
}
public String toString() {
Node<Item> curr = first;
String s = "";
while (curr != null) {
s += curr.item.toString() + " ";
curr = curr.next;
}
s += "\n";
return s;
}
public static void main (String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
Node<Integer> a = new Node<Integer>(new Integer(1));
Node<Integer> b = new Node<Integer>(new Integer(2));
Node<Integer> c = new Node<Integer>(new Integer(3));
Node<Integer> d = new Node<Integer>(new Integer(4));
list.add(a);
list.add(b);
list.add(c);
list.add(d);
System.out.println(list.toString());
list.delete(b); // wanna delete b, but actually we delete c
System.out.println(list.toString());
list.delete(b); // delete d, an error would ocur if tryidng delete c
System.out.println(list.toString());
}
}
public class Node<Item> {
public Item item;
public Node<Item> next;
public Node (Item item) {
this.item = item;
this.next = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment