链接列表:将节点从一个列表移动到另一个列表

时间:2013-12-17 14:05:37

标签: c pointers linked-list

有2个列表source={3,2,1}dest ={4,5,6,7},其中链接列表的头指针分别位于3和4中。删除源头节点,将数据3移动到dest列表,并将其作为dest列表中的新头节点。

所以在第一轮source ={2,1} dest ={3,4,5,6,7}之后,源头中的头部现在指向2,而头部的头部指向3.最后我必须做source = NULL and Dest = {1,2,3,4,5,6,7} head => 1。我可以通过每次调用下面的移动节点函数来做到这一点。但是当我在循环中运行它会保持循环。这是错误的代码。请告诉我为什么会出现循环问题。

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

请检查移动节点While循环部分。

2 个答案:

答案 0 :(得分: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;  
}

答案 1 :(得分:0)

答案与@ zavg的答案略有不同。一点点的调整使它工作正常。

正如我所说,源指针也应该改变。所以我将粘贴代码。谢谢@zavg的帮助。

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