Linked List(Insert Delete Reverse search display) in Java

//This is the class that I use to make the node. Here I use a constructor to add the element in a node.

//next gets automatically initialized as null.

public class link {

int i;

link next;

public link(int j)

{

i = j;

}

}

**********************************************

//This is the main class where all the methods and work is taking place.

public class list {

link first;

public list()

{

first = null;

}

public void insertatstart(int d)

{

link newlink  = new link(d);

newlink.next = first;

first = newlink;

}

public link delfirst()

{

link temp = first;

first = first.next;

return temp;

}

public void displaylist()

{

link curr = first;

System.out.println(“Printing the linked list”);

while(curr != null)

{

System.out.println(curr.i);

curr = curr.next;

}

}

public void insertlast(int s)

{

link curr = first;

while(curr.next != null)

{

curr = curr.next;

}

link newlink = new link(s);

newlink.next = curr.next;

curr.next = newlink;

}

public void insspeclinks(int t, int j)

{

link curr = first;

while(curr.i != t)

{

curr = curr.next;

}

link newlink = new link(j);

newlink.next = curr.next;

curr.next = newlink;

}

public void delspeclink(int key)

{

link curr = first;

link prev = first;

while(curr.i != key)

{

prev = curr;

curr = curr.next;

}

prev.next = curr.next;

curr = null;

}

public void reverse()

{

link temp = null;

link curr = first;

link next = curr.next;

while(next != null)

{

curr.next = temp;

temp = curr;

curr = next;

next = next.next;

}

first = curr;

first.next = temp;

}

}

**********************************************

//Tester class to test the program

public class linktest {

public static void main(String [] args)

{

list l = new list();

l.insertatstart(3);

l.insertatstart(6);

l.insertatstart(7);

l.insertatstart(8);

l.displaylist();

l.insertlast(111);

l.insertlast(222);

l.insertlast(333);

l.displaylist();

l.delfirst();

l.delfirst();

l.displaylist();

l.insspeclinks(111, 112);

l.displaylist();

l.delspeclink(222);

l.displaylist();

l.reverse();

System.out.println(“rev”);

l.displaylist();

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s