bks4line
bks4line

Reputation: 515

Linked List: Moving a node from one list to another

There are 2 lists source={3,2,1} and dest ={4,5,6,7} where the head pointer of the linked lists are there in 3 and 4 respectively. head node from source is deleted and the data 3 is moved to dest list and it is made as new head node in dest list.

So after first round source ={2,1} dest ={3,4,5,6,7} where head in source is pointing to 2 now and head in dest is pointing to 3. Finally I have to make source = NULL and Dest = {1,2,3,4,5,6,7} head => 1. I can do that by calling the move node function below every time. But when i run in a loop it keeps looping. Here is the erroneous code. Please tell me why there is a looping problem.

     typedef struct node{
int data;
struct node* next;
}Node;

    void push(Node** headRef, int data){
Node* newNode = (Node*) malloc(sizeof(newNode));
newNode->data = data;
newNode->next = *headRef;
*headRef = newNode;
    }
    Node* pushtop(){
Node* head = NULL;
int i;
for(i = 1; i<=3; i++){
push(&head,i);
}
return head; 
    }

    Node* pushbottom(){
Node* head = NULL;
int i;
for(i=7; i>=4; i--){
push(&head,i);
}
return head;
    }

    void moveNode(Node** source,Node** dest){
Node* ptr = *source;
Node* current = NULL;
while(ptr!=NULL){    // here the continuous looping occurs 
    current=ptr;
    current->next = *dest
    *dest = current;    
    *source = ptr->next;
    ptr = ptr->next;
    }
    Node* test = *dest;
    printf("\nthe then moved list is\n\n");
    while(test!=NULL){
        printf("%d\n",test->data);
        test = test->next;
        }
      } 
    int main(){
Node* headA = pushtop();
Node* headB = pushbottom();
moveNode(&headA, &headB);
    return 0;
}

please check Move node While loop part.

Upvotes: 1

Views: 9567

Answers (2)

bks4line
bks4line

Reputation: 515

The Answer is a bit different from @zavg's answer. a little bit of tweaking made it work fine.

As i said the source pointer should also be changed. so i will paste the code. Thanks @zavg for the help.

     while(ptr != NULL) {    // here is the correct code. 
         current = ptr->next;
         ptr->next = *dest;
        *dest = ptr;     
         ptr = current;
        *source = ptr;  
       }

        printf("%p\n",*source);   //it will print Nil.

        Node* test = *dest;
        printf("\nthe then moved list is\n\n");

        while(test!=NULL){
            printf("%d\n",test->data);
            test = test->next;
        }

Upvotes: 0

zavg
zavg

Reputation: 11061

Node* ptr = NULL;
Node* current = *source;
while(current != NULL) {    // here the continuous looping occurs 
    ptr = current->next;
    current->next = dest;
    dest = current;     
    current = ptr;  
}

Upvotes: 2

Related Questions