链接列表:从一个列表移动一个节点到另一个 [英] Linked List: Moving a node from one list to another
问题描述
有2列出源= {3,2,1}
和 DEST = {4,5,6,7}
其中链表的头指针分别有3个和4个。从源头节点被删除,数据3被移动到dest列表,它是由作为在dest列表新头节点。
There are 2 lists source={3,2,1}
and dest ={4,5,6,7}
where the head pointer of the linked lists are there in 3 and 4 respectively. head node from source is deleted and the data 3 is moved to dest list and it is made as new head node in dest list.
所以,首轮过后源= {2,1} DEST = {3,4,5,6,7}
,其中头部源指向2现在头在dest指向3.最后我不得不做出源= NULL和dest = {} 1,2,3,4,5,6,7头=> 1
。我可以通过调用每次下方移动节点的功能做到这一点。但是,当我在一个循环中运行它不断循环。这是错误的code。请告诉我为什么有一个循环的问题。
So after first round source ={2,1} dest ={3,4,5,6,7}
where head in source is pointing to 2 now and head in dest is pointing to 3. Finally I have to make source = NULL and Dest = {1,2,3,4,5,6,7} head => 1
. I can do that by calling the move node function below every time. But when i run in a loop it keeps looping. Here is the erroneous code. Please tell me why there is a looping problem.
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循环的一部分。
please check Move node While loop part.
推荐答案
答案是从@ zavg的回答有点不同。调整一点点使它正常工作。
The Answer is a bit different from @zavg's answer. a little bit of tweaking made it work fine.
正如我所说,源指针也应该有所改变。所以我将粘贴code。感谢@zavg的帮助。
As i said the source pointer should also be changed. so i will paste the code. Thanks @zavg for the help.
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;
}
这篇关于链接列表:从一个列表移动一个节点到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!