top of page
Search

Write code to partition a linked list around a value x, such that all nodes less than x come before

  • Writer: Abhinaw Tripathi
    Abhinaw Tripathi
  • May 26, 2016
  • 1 min read

Approach:

We iterate through the linked list ,inserting elements into our before list or our after list.Once we reach the end of the linked list and have completed this splitting we merge the two lists.

Solution:

public LinkedListNode partition(LinkedListNode node ,int x)

{

LinkedListNode beforeStart = null;

LinkedListNode beforeEnd = null;

LinkedListNode afterStart = null;

LinkedListNode afterEnd = null;

while(node!=null)

{

LinkedListNode next =node.next;

node.next = null;

if(node.data < x)

{

if(beforeStart == null)

{

beforeStart =node;

beforeEnd=beforeStart;

}

else

{

beforeEnd.next =node;

beforeEnd=node;

}

}

else

{

if(afterStart == null)

{

afterStart =node;

afterEnd =afterStart;

}

else

{

afterEnd.next =node;

afterEnd=node;

}

}

node =next;

}

if(beforeStart == null)

return afterStart;

beforeEnd.next =afterStart;

return beforeStart;

}

 
 
 

Recent Posts

See All

Komentarji


© 2016 by Abhinav Tripathi

  • Facebook Clean Grey
  • Twitter Clean Grey
bottom of page