/* related posts with thumb nails */

Program to split 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 split(int p,LinkedList l2)

{

node ptr=first;

for(int i=1;i<=p-1;i++)

ptr=ptr.next;

l2.first=ptr.next;

ptr.next=null;

}

void show()

{

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

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

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

}

}

class SplitList

{

public static void main(String as[])

{

LinkedList l1=new LinkedList();

l1.add(30);

l1.add(40);

l1.add(50);

l1.add(60);

l1.add(60);

l1.show();

l1.split(3,l2); // splitting at position 3

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

l1.show();

l2.show();

}

}

/* Output */

List Elements:

30 40 50 60 70

After Slitting:

List Elements:

30 40

List Elements:

50 60 70

Related Topics:

0 comments:

Post a Comment