/* related posts with thumb nails */

Program to reverse a single linked list:

class node

{

public int x;

public node next;

}

class LinkedList

{

public node first;

LinkedList()

{

first=null;

}

void add (int v)

{

node temp=new node();

temp.x=v;

temp.next=null;

if(first==null)

first=temp;

else

{

node ptr=first;

while(ptr.next!=null)

ptr=ptr.next;

ptr.next=temp;

}

}

void reverse()

{

for(node p1=first;p1.next!=null;p1=p1.next)

for(node p2=p1.next;p2!=null;p2=p2.next)

{

int t=p1.x;

p1.x=p2.x;

p2.x=t;

}

}

void show()

{

System.out.println("\nList Elements:");

for(node ptr=first;ptr!=null;ptr=ptr.next)

System.out.print("\t"+ptr.x);

}

}

class RListTest

{

public static void main(String as[])

{

LinkedList l1=new LinkedList();

l1.add(30);

l1.add(40);

l1.add(50);

l1.add(60);

l1.show();

l1.reverse();

System.out.println("\nAfter Reversing:");

l1.show();

}

}

/* Output */

List Elements:

30 40 50 60

After Reversing:

List Elements:

60 50 40 30

Related Topics:

0 comments:

Post a Comment