33.png

    1. /*
    2. 设A、B是两个单链表(带头结点),其中元素递增有序,设计一个算法从A、B中的公共元素产生单链表C,要求不破坏A、B节点
    3. 分析:
    4. 要求不破坏A、B节点,故我们需要重新创建分配节点空间,来进行连接。为寻找公共元素,每遍历A中的一个元素,都去
    5. 与B中元素一一比较,同则取值给另一空间节点,连接到C上。时间复杂度为O(n^2)。
    6. 因为这两个链表是递增有序的,那么我们可以设置两个指针同步比较,相同则加入c,不同小的那个往后移,直至到链表末尾
    7. 这样的时间复杂度为O(n).
    8. */
    9. struct Link {
    10. int data;
    11. struct Link *next;
    12. };
    13. #include <stdlib.h>
    14. #include <stdio.h>
    15. void linkCommon(Link *a, Link *b, Link *c ) {
    16. struct Link *lc = c,*la=a->next,*lb=b->next,*rc=lc;
    17. while (la) {
    18. while (lb) {
    19. if (la->data==lb->data) {//如果是公共元素
    20. struct Link *p = (struct Link*)malloc(sizeof(struct Link));
    21. p->data = la->data;
    22. rc->next = p;//采用尾插法
    23. rc = p;
    24. break;
    25. }
    26. lb = lb->next;
    27. }
    28. la = la->next;
    29. lb = b->next;
    30. }
    31. rc->next = NULL;//最后一个节点指针需要指向NULL。
    32. }
    33. void listCommon(Link *a,Link *b,Link *c) {
    34. struct Link *rc = c, *la = a->next, *lb = b->next;
    35. while (la&&lb) {
    36. if (la->data==lb->data) {
    37. struct Link *p = (struct Link*)malloc(sizeof(struct Link));
    38. p->data = la->data;
    39. p->next = NULL;
    40. rc->next = p;
    41. rc = p;
    42. la = la->next;
    43. lb = lb->next;
    44. }
    45. else {
    46. la->data < lb->data ? la = la->next : lb = lb->next;
    47. }
    48. }
    49. rc->next = NULL;
    50. }
    51. int main() {
    52. struct Link *a, *b;
    53. Link *createLink(int);
    54. void printfNowLink(Link *);
    55. a = createLink(0);
    56. b = createLink(0);
    57. struct Link *c = (struct Link*)malloc(sizeof(struct Link));
    58. c->next = NULL;
    59. //linkCommon(a,b,c);
    60. listCommon(a,b,c);
    61. printfNowLink(c);
    62. return 0;
    63. }