有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循环部分。
逻辑上我的代码必须工作。我错过了可视化的东西,导致循环。它在Source的头部和dest头部之间循环。 – bks4line
你确定不会崩溃吗?我在移动中看到的第一件事是current = NULL; ptr =当前; ptr-> next = * dest; ---->分段故障<---- –
费尔南多编辑哥们!对不起,错误 – bks4line