Skip to content

Instantly share code, notes, and snippets.

@alexandervasyuk
Created October 18, 2014 03:21
Show Gist options
  • Save alexandervasyuk/3f2514f4e65945a84996 to your computer and use it in GitHub Desktop.
Save alexandervasyuk/3f2514f4e65945a84996 to your computer and use it in GitHub Desktop.
remove element from double linked list
public class DoublyLinkedList {
Node head;
Node tail;
public Node getHead() {
return head;
}
public Node getTail() {
return tail;
}
public void append(int d) {
if (head == null) {
head = tail = new Node(d);
} else {
Node n = new Node(d);
tail.setNext(n);
n.setParent(tail);
tail = tail.getNext();
}
}
public Node remove(int d) {
if (head == null) return null;
while (head != null && head.getData() == d) {
Node next = head.getNext();
if (next != null) next.setParent(null);
head = next;
}
if (head != null) {
Node prev = head;
Node current = head.getNext();
while (current != null) {
if (current.getData() == d) {
Node curNext = current.getNext();
prev.setNext(curNext);
if (curNext != null) curNext.setParent(prev);
current = curNext;
} else {
prev = prev.getNext();
current = current.getNext();
}
}
}
return head;
}
public void print() {
while (head.getNext() != null) {
System.out.print(head.getData() + " -> ");
head = head.getNext();
}
System.out.println(head.getData());
}
}
public class Node {
private Node next;
private Node parent;
private Integer data;
public Node(int d) {
data = d;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setParent(Node n) {
parent = n;
}
public Node getParent() {
return parent;
}
public Integer getData() {
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment