Created
June 1, 2018 12:21
-
-
Save peanutpi/bbf6e9c0d8ae30ff030b0c78a01bae3a to your computer and use it in GitHub Desktop.
Test Doubly Linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DoublyLinkedListImpl { | |
private Node head; | |
private Node tail; | |
private int size; | |
public DoublyLinkedListImpl() { | |
size = 0; | |
} | |
/** | |
* this class keeps track of each data | |
*/ | |
private class Node { | |
int data; | |
Node next; | |
Node prev; | |
public Node(int data, Node next, Node prev) { | |
this.data = data; | |
this.next = next; | |
this.prev = prev; | |
} | |
} | |
/** | |
* adds data at the starting of the linked list | |
* @param data | |
*/ | |
public void addFirst(int data) { | |
Node tmp = new Node(data, head, null); | |
if(head != null ) {head.prev = tmp;} | |
head = tmp; | |
if(tail == null) { tail = tmp;} | |
size++; | |
System.out.println("adding: "+data); | |
} | |
/** | |
* adds data at the end of the linked list | |
* @param data | |
*/ | |
public void addLast(int data) { | |
Node tmp = new Node(data, null, tail); | |
if(tail != null) {tail.next = tmp;} | |
tail = tmp; | |
if(head == null) { head = tmp;} | |
size++; | |
System.out.println("adding: "+data); | |
} | |
/** | |
* this method walks forward through the linked list | |
*/ | |
public void iterate(){ | |
System.out.println("iterating forward.."); | |
Node tmp = head; | |
while(tmp != null){ | |
System.out.print(tmp.data+","); | |
tmp = tmp.next; | |
} | |
System.out.println(); | |
} | |
/** | |
* this method removes all the nodes that has data greater than x | |
* @param head | |
* @param x | |
*/ | |
public void deleteNode(Node head, int x) | |
{ | |
if(head==null) | |
return; | |
if(size == 1 && head.data > x){ | |
head.next.prev = null; | |
return; | |
} | |
Node temp = head; | |
while (temp.next != null){ | |
Node current = temp.next; | |
if(current.data > x){ | |
current.prev.next = current.next; | |
if(current.next != null) | |
current.next.prev = current.prev; | |
} | |
temp = current; | |
} | |
return; | |
} | |
public static void main(String a[]){ | |
DoublyLinkedListImpl dll = new DoublyLinkedListImpl(); | |
dll.addFirst(10); | |
dll.addFirst(34); | |
dll.addLast(56); | |
dll.addLast(364); | |
dll.addLast(1200); | |
dll.addLast(589); | |
dll.addLast(12); | |
dll.addLast(5000); | |
dll.iterate(); | |
dll.deleteNode(dll.head, 50); | |
dll.iterate(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment