7-52、两个有序链表序列的交集

刺骨的言语ヽ痛彻心扉 2022-10-27 01:36 227阅读 0赞

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

  1. 1 2 5 -1
  2. 2 4 5 8 10 -1

输出样例:

  1. 2 5

一开始用Java写了两遍,都无法全部通过,最后一个样例不是运行超时就是内存超限,有用Java通过的小伙伴们交流一下,本题无奈只能转C了。

思路:一对一比对,谁小谁next,尾插法创建链表,交集没有新建节点,而是取S1的节点,破坏了S1的链表。
其他思路:使用一条S1链表即可,在S2输入数字的时候就进行比对,取交集,
AC代码:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedef struct Node{
  4. int value;
  5. struct Node* next;
  6. }*Link;
  7. Link createLink(){
  8. Link head,tail,node;
  9. int value;
  10. head = (Link)malloc(sizeof(struct Node));
  11. head->next = NULL;
  12. tail = head;
  13. while(scanf("%d",&value),value!=-1){
  14. node = (Link)malloc(sizeof(struct Node));
  15. node->value = value;
  16. node->next = NULL;
  17. tail->next = node;
  18. tail = tail->next;
  19. }
  20. return head;
  21. }
  22. Link intersection(Link S1,Link S2){
  23. Link S3,tail;
  24. Link L1,L2;
  25. if(S1 == NULL || S1->next == NULL || S2 == NULL || S2->next == NULL){
  26. return NULL;
  27. }
  28. L1 = S1->next;
  29. L2 = S2->next;
  30. S3 = (Link)malloc(sizeof(struct Node));
  31. S3->next = NULL;
  32. tail = S3;
  33. while(L1 != NULL && L2 != NULL){
  34. if(L1->value > L2->value){
  35. L2 = L2->next;
  36. }else if(L1->value < L2->value){
  37. L1 = L1->next;
  38. }else{
  39. tail->next=L1;
  40. L1 = L1->next;
  41. L2 = L2->next;
  42. tail = tail->next;
  43. tail->next = NULL;
  44. }
  45. }
  46. return S3;
  47. }
  48. void print(Link S){
  49. Link tail;
  50. if(S == NULL || S->next == NULL) {
  51. printf("NULL\n");
  52. return ;
  53. }
  54. tail = S->next;
  55. while(tail->next != NULL){
  56. printf("%d ",tail->value);
  57. tail = tail->next;
  58. }
  59. printf("%d\n",tail->value);
  60. }
  61. int main(){
  62. Link S1,S2,S3;
  63. S1 = createLink();
  64. S2 = createLink();
  65. S3 = intersection(S1,S2);
  66. print(S3);
  67. return 0;
  68. }

发表评论

表情:
评论列表 (有 0 条评论,227人围观)

还没有评论,来说两句吧...

相关阅读