【发布时间】: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