Skip to content

Instantly share code, notes, and snippets.

@sdmg15
Created October 8, 2017 11:24
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 sdmg15/74ed10ef549047c829e4e21c2c2128ff to your computer and use it in GitHub Desktop.
Save sdmg15/74ed10ef549047c829e4e21c2c2128ff to your computer and use it in GitHub Desktop.
A simple linked list
public class LL {
class Node{
int data;
Node next;
Node prev;
public Node(int data){
this.data = data;
this.next = null;
this.prev = null;
}
}
Node head;
int size;
public void append(int data){
if(head== null) head = new Node(data);
else {
Node newHead = new Node(data);
head.prev = newHead;
newHead.next = head;
head = newHead;
}
size++;
}
public void push(int data){
Node tmp = head;
if(head == null) head = new Node(data);
while (tmp.next !=null){
tmp = tmp.next;
}
Node newNode = new Node(data);
tmp.next = newNode;
newNode.prev = tmp;
size++;
}
public void printList(){
Node tmp = head;
while(tmp != null){
System.out.print("Adress : " + tmp + " " + tmp.data+" " +tmp.prev+ "\n");
tmp = tmp.next;
}
}
public void reverse(){
Node tmpHead = head;
int numberOfOperations = this.getSize()/2;
Node tail;
//We first find the tail...
while( tmpHead.next != null){
tmpHead = tmpHead.next;
}
tail = tmpHead;
int i = 0;
Node tmpHeads = head;
while (i < numberOfOperations){
int tmpData = tmpHeads.data;
tmpHeads.data = tail.data;
tail.data =tmpData;
tmpHeads = tmpHeads.next;
tail = tail.prev;
i++;
}
}
public void remove(int data){
Node tmp = head;
if(head ==null) return;
if(head.data == data ){
head.next.prev = null;
head = head.next;
return;
}
while(tmp.next != null){
if(tmp.next.data == data){
Node node = tmp.next;
node.prev.next = node.next;
node.next.prev = node.prev.next;
}
tmp = tmp.next;
}
}
//Sort the linked list ...
public void sort(){
}
public int getSize(){
return this.size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment