top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Split a LinkList based on alternate element?

+1 vote
77 views

Say you are given a linklist as {a, b, a, b, a} , you need to divides up its nodes to make two smaller lists. The sublists should be made from alternating elements in the original list. So in this case one sublist should be {a, a, a} and the other should be {b, b}.

posted Nov 6, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+1 vote

Try something like this

/* Take the node from the front of the source, and move it to the front of the dest.
   It is an error to call this with the source list empty. */
void MoveNode(struct node** destRef, struct node** sourceRef) 
{
  /* the front source node  */
  struct node* newNode = *sourceRef; 

  /* Advance the source pointer */
  *sourceRef = newNode->next;

  /* Link the old dest off the new node */
  newNode->next = *destRef; 

  /* Move dest to point to the new node */
  *destRef = newNode; 
}

void AlternatingSplit(struct node* source, struct node** aRef, struct node** bRef) 
{
  /* split the nodes of source to these 'a' and 'b' lists */
  struct node* a = NULL; 
  struct node* b = NULL;

  struct node* current = source;
  while (current != NULL) 
  {
    MoveNode(&a, &current); /* Move a node to list 'a' */
    if (current != NULL) 
    {
       MoveNode(&b, &current); /* Move a node to list 'b' */
    }
  }
  *aRef = a;
  *bRef = b;
}
answer Nov 6, 2013 by Salil Agrawal
Similar Questions
+3 votes

How to delete the node that given as argument in single linked list?
Is there any system call to get prev pointer ?

Note: Here the goal is to delete the address not the node's value

+3 votes

Is it possible if yes can someone share the code in C?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...