Splitting linked list

Given a list, split it into two sublists — one for the front half, and one for the back half. If the number of elements is odd, the extra element should go in the front list. So FrontBackSplit() on the list {2, 3, 5, 7, 11} should yield the two lists {2, 3, 5} and {7, 11}.

C++:
01 Node* split(Node* head)
02 {
03     Node* fast=head;
04     Node* slow=head;
05     while(true){
06         fast=fast->next;
07         if(!fast)
08             break;
09         fast=fast->next;
10         if(!fast)
11             break;
12         slow=slow->next;
13     }
14     fast=slow->next;
15     slow->next=NULL;
16     return fast;
17 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s