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.
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("
the then moved list is
");
while(test!=NULL){
printf("%d
",test->data);
test = test->next;
}
}
int main(){
Node* headA = pushtop();
Node* headB = pushbottom();
moveNode(&headA, &headB);
return 0;
}
please check Move node While loop part.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…