2013-12-17 146 views
0

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

所以在第一轮source ={2,1} dest ={3,4,5,6,7}之后,现在head的源代码指向2,head代表dest指向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循环部分。

+0

逻辑上我的代码必须工作。我错过了可视化的东西,导致循环。它在Source的头部和dest头部之间循环。 – bks4line

+3

你确定不会崩溃吗?我在移动中看到的第一件事是current = NULL; ptr =当前; ptr-> next = * dest; ---->分段故障<---- –

+0

费尔南多编辑哥们!对不起,错误 – bks4line

回答

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

啊,我不认为'dest'和'source'是'Node **'中的你的情况。我只是发布一般算法的想法:) – zavg

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

我收到分割代码!此外源指针也应该移动。请帮帮我。谢谢!我可以给出正确的答案。它的工作与微调。 – bks4line

+0

完美!谢谢哥们!我意识到我的错误。我用ptr指针连接目标指针而不是当前指针!按我的预期工作。万分感谢! :) – bks4line

+0

如果您喜欢它,请将其标记为答案,并将其归功于以下方面:-) –

相关问题