算法练习-2

已知单调递增的单链表A,B,求A-B(差集),结果保存在A链表,并保持单调递增。其中:A,B有头结点。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct LNode
 5 {
 6     int data;
 7     LNode *next;
 8 }LNode;
 9 
10 LNode* createLink(int a[],int len)
11 {
12     LNode *head=(LNode*)malloc(sizeof(LNode));
13     head->next=NULL;
14     LNode *q=head;
15     for(int i=0;i<len;i++)
16     {
17         LNode *p=(LNode*)malloc(sizeof(LNode));
18         p->data=a[i];
19         p->next=NULL;
20         q->next=p;
21         q=q->next;
22     }
23     return head;
24 }
25 
26 void print(LNode*head)
27 {
28     LNode*p=head->next;
29     printf("开始打印\n");
30     while(p)
31     {
32         printf("%d \t", p->data);
33         p=p->next;
34     }
35     printf("\n结束打印\n");
36 }
37 
38 void f(LNode *A,LNode *B)//已知各自有序的链表A,B,求差集A-B,结果写回A链表
39 {
40     LNode *p,*q,*pre;
41     pre=A,p=pre->next,q=B->next;
42     while(p && q)
43     {
44         if(p->data < q->data)
45         {
46             p=p->next;
47             pre=pre->next;
48         }
49         else if(p->data == q->data)
50         {
51             pre->next=p->next;
52             p=p->next;
53         }
54         else
55         {
56             q=q->next;
57         }
58     }
59 }
60 int main(int argc, char const *argv[])
61 {
62     int a[]={1,2,3,4,5,6};
63     int aLen=sizeof(a)/sizeof(int);
64     int b[]={1,3,5};
65     int bLen=sizeof(b)/sizeof(int);
66     LNode *A=createLink(a,aLen);
67     LNode *B=createLink(b,bLen);
68 
69     f(A,B);
70     print(A);
71     return 0;
72 }

运行结果:

 

posted @ 2019-11-20 21:25  细雨轻风  阅读(171)  评论(0编辑  收藏  举报