Reputation: 39
I wanna merge two singly linked list like La and Lb into new list like Lc, and lc's head node point to La. There is the code:
//something unnecessary code has been cut
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
//merge La and Lb into Lc
Status Algo(LinkList La, LinkList *Lb, LinkList *Lc);
int main()
{
LinkList La,Lb,Lc;
CreateListHead_L(&La, 5); //Crate a list with 5 nodes
CreateListHead_L(&Lb, 5);
printf("La:"); ListTraverse_L(La);
printf("Lb:"); ListTraverse_L(Lb);
Algo(La, &Lb, &Lc);
printf("Lc:");
ListTraverse_L(Lc);
return 0;
}
Status Algo(LinkList La, LinkList *Lb, LinkList *Lc)
{
LinkList p;
*Lc = La;
p = La->next;
if(!p) return ERROR;
while(p)
p = p->next;
p->next = (*Lb)->next;
free(*Lb);
return OK;
}
I just wanna know what wrong with the function Algo
which I think that is right. Why the program would crashed when it process the function?
Upvotes: 0
Views: 45
Reputation: 74605
Surely this will run off the end of La and you'll end up holding nothing when what you actually want to be holding is the last node in La, so you can set its next to be the head of Lb (your while loop is trying to find the last node in La but it goes too far and only stops looping after it runs off the end of the list)
I don't do c, but I understand the logic.. really you want to be doing something like
while(p->next) //while there is still a next item
So that when you get to the last item in La, the loop stops and your p is still the last item, not null
Upvotes: 2