Linked List: Moving a node from one list to another

假如想象 提交于 2019-12-11 19:06:10

问题


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.


回答1:


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



回答2:


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;
        }


来源:https://stackoverflow.com/questions/20636265/linked-list-moving-a-node-from-one-list-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!