Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

c - 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("
the then moved list is

");
    while(test!=NULL){
        printf("%d
",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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...