Skip to content

Instantly share code, notes, and snippets.

@pavelnganpi
Last active August 29, 2015 14:04
Show Gist options
  • Save pavelnganpi/a0aebfd86646f6b944a1 to your computer and use it in GitHub Desktop.
Save pavelnganpi/a0aebfd86646f6b944a1 to your computer and use it in GitHub Desktop.
package test;
public class Link {
public static class LinkedList<E>{
public class Node<E>{
E elem;
Node<E> next,previous;
}
public LinkedList(){};
Node<E> temp = null;
Node<E> head = null;
Node<E> tail = null;
int counter = 0;
public int size(){
return counter;
}
//get element at the index
public E getI(int index){
assert(index>=0 && index<size());
temp = head;
for(int i = 0; i< index;i++){//scan tru list and find the index
temp = temp.next;
}
return temp.elem;
}
//get index of an element
public int getE(E elem){
temp = head;
int cnt = 0;
//traverse through list and find element
while(temp != null && !temp.elem.equals(elem)){
cnt++;
temp = temp.next;
}
if(cnt == size()){return -1;};
return cnt;
}
//add a node at the tail
public void add(E elem){
//if head is null create new node
if(head == null){
head = new Node<E>();
tail = head;
head.elem = elem;
head.next = tail;
}
else{
tail.next = new Node<E>(); //tail's next becomes newnode
tail = tail.next; // tail is new node
tail.elem = elem;
tail.next = null;
}
counter++;
}
//remove method
public void remove(int index){//little bug, deletes 1st and 2nd element when remove(0)
assert(index>=0 && index<size());
// temp = head;
if(index == 0){
head = head.next;
counter--;
}
else{
temp = head;
for(int i = 0;i<index-1; i++){
temp = temp.next;
}
Node<E> two = new Node<E>();
two = temp.next;
temp.next = two.next;
E hold = two.elem;
two = null;
counter--;
//return hold;
}
}
public void removeE(E elem){
if(elem.equals(head.elem)){
head = head.next;
counter--;
}
else if(elem.equals(tail.elem)){
tail =tail.previous;
//tail.next = null;
counter--;
}
else{
Node<E> two = new Node<E>();
temp = head;
while(temp!=null && !temp.elem.equals(elem)){
two = temp;
temp = temp.next;
}
if(temp == null){System.out.println("elem doesn not exist");
}
else{
two.next = temp.next;
counter--;
}
}
}
public void addI(int index, E elem){
if(index == size()){add(elem);}
else if(index == 0){
Node<E> now = new Node<E>();
now.elem = elem;
now.next = head;
head.previous = now;
head = now;
counter++;
}
else{
temp = head;
for(int i = 0; i< index-1; i++){
temp = temp.next;
}
Node<E> myNode = new Node<E>();
myNode.elem = elem;
myNode.next = temp.next;
temp.next = myNode;
counter++;
}
}
public static void main(String[]args){
LinkedList<Integer> linklist = new LinkedList<Integer>();
linklist.add(1);
linklist.add(2);
linklist.add(3);
linklist.addI(0,4);
linklist.addI(1,5);
linklist.removeE(5);
for(int i=0;i<linklist.size();i++){
System.out.println(linklist.getI(i));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment