【问题标题】:Linked List: Moving a node from one list to another链表:将节点从一个列表移动到另一个列表
【发布时间】:2013-12-17 14:05:36
【问题描述】:

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

所以在第一轮 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 循环部分。

【问题讨论】:

  • 逻辑上我的代码必须工作。我错过了可视化导致循环的东西。它在 Source 的头和 dest 的头之间循环!
  • 您确定不会崩溃吗?我在这里看到的第一件事是 current = NULL; ptr = 当前; ptr->下一个 = *dest; ----> 分段错误
  • fernando 编辑的朋友!抱歉弄错了
  • 你是怎么把压痕拧得这么厉害的?
  • 在发布代码之前,请正确格式化。

标签: c pointers linked-list


【解决方案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;  
}

【讨论】:

  • 我得到了分段代码转储!而且源指针也应该被移动。请帮我。谢谢!我能给出正确答案吗?它需要进行一些调整。
  • 完美!谢谢哥们!我意识到我的错误。我使用 ptr 指针连接目标指针而不是当前指针!按我的预期工作。万分感谢! :)
  • 如果您喜欢它,请将其标记为答案并在应得的地方给予赞誉:-)
  • @bks4line 感谢您的情感反馈 :)
【解决方案2】:

答案与@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;
        }

【讨论】:

  • 啊,我不认为 destsource 在你的情况下是 Node**。我只是发布一般的算法思想:)
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多