有两个单链表A,B。函数Difference()是用于求解A,B之间差集,并将结果保存在A集合中,具体如下:
链表节点的结构是这样的。
- typedef struct Node
- {
- int num;
- Node *next;
- }NodeType;
已知
链表A: head-> 5 -> 10 -> 20 -> 15 -> 25 -> 30 -> null
链表B: head-> 5 -> 15 -> 35 -> 25 -> null
结果
链表A: head-> 10 -> 20 -> 30 -> null
链表B: head-> 5 -> 15 -> 35 -> 25 -> null
答案代码如下:
- void Difference(NodeType **LA,NodeType *LB)
- {
- node *pa,*pb,*pre;
- pre= NULL;
- pa=*LA; //(1)
- while(pa)
- {
- pb=LB;
- while((pb!=NULL)&&(pb->num!=pa->num)) //(2)
- {
- pb=pb->next;
- }
- if(pb!=NULL) //(3)
- {
- if(!pre)
- {
- *LA=pa->next; //(4)
- }
- else
- {
- pre->next=pa->next; //(5)
- }
- q=pa;
- pa=pa->next;
- free(q);
- }
- else
- {
- pre=pa; //(6)
- pa=pa->next;
- }
- }
- }