0

I am having some problem when trying to split a linked list into half. Let's say for example my linked list is 2,3,5,6,7. And the first split linked list should contain 2,3,5 and the second one should be 6,7.

I have not actually came out with the code yet as I still need some helps in the pseud code.

int check = size%2
if even
  int half = size/2
  while(ctrFront < half)
    front.insertNode; ctrFront++; update head pointer;
  while(ctrBack < half)
    back.insertNode; ctrBack++; update head pointer;
if odd
  int half = size/2 round up
  while(ctrFront < half + 1)
    front.insertNode; ctrFront++; update head pointer;
  while(ctrBack < half)
    back.insertNode; ctrBack++; update head pointer;

I not sure if this is the correct way as the logic seems a little bit wrong. Any guides?

Thanks in advance.

1 Answers1

0

Construct two lists. Pop the source list until its is empty, pushing each item alternately onto the new lists. Reseat the head pointer of the source list with one of the new lists.

There, it's easy:

linkedList *newList1=NULL;
linkedList *newList2=NULL;

while(true){
  node *temp;
  node=listPop(&sourceList);
  if(temp==NULL) break;
  listPush(&newList1,temp);
  temp=listPop(&sourceList);
  if(temp==NULL) break;
  listPush(&newList2,temp);
};
Martin James
  • 24,453
  • 3
  • 36
  • 60
  • But I didn't want to store them alternately. Mine was just simply splitting into front and back part –  Oct 31 '15 at 14:15