ytu 2231: 交集问题(线性表)(数据结构,链表练习)

2231: 交集问题(线性表)

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 6   Solved: 3
[ Submit][ Status][ Web Board]

Description

设有两个单链表A,B,求出A,B的交集元素放到A中

Input

1 4 5 6 7 8

 

1 3 6 9 10 33

Output

1 6

Sample Input

11 14 54 6 4 83
 
11 3 6 9 10 83

Sample Output

11 6 83

HINT

 

Source

  

  数据结构链表练习

  对两个链表取交集输出。考验链表的实现和处理。作为练习题很适合。也纠结了不少时间。

  代码:

 1 #include <iostream>
 2 #include <stdio.h>
 3 using namespace std;
 4 struct Node{
 5     int num;
 6     Node* next;
 7 };
 8 int main()
 9 {
10     int n=0;
11     char c;
12     Node* head = new Node;
13     Node* p = new Node;
14     head->next = p;
15     //输入A链表
16     while((c=getchar())!='\n'){
17         if('0'<=c && c<='9'){ //c是数字
18             int t = c-'0';
19             n = n*10+t;
20         }
21         else if(c==' ' && n!=0){    //c是空格
22             p->num = n;
23             n = 0;
24             Node* cur = new Node;
25             p->next = cur;
26             p=cur;
27         }
28     }
29     p->num = n;
30     p->next = NULL;
31 
32     getchar();    //两个链表中间有一个回车
33 
34     Node* head2 = new Node;
35     Node* p2 = new Node;
36     p = p2;
37     head2->next = p;
38     n = 0;
39     //输入A链表
40     while((c=getchar())!='\n'){
41         if('0'<=c && c<='9'){ //c是数字
42             int t = c-'0';
43             n = n*10+t;
44         }
45         else if(c==' ' && n!=0){    //c是空格
46             p->num = n;
47             n = 0;
48             Node* cur = new Node;
49             p->next = cur;
50             p=cur;
51         }
52     }
53     p->num = n;
54     p->next = NULL;
55 
56     //取交集,对A链表处理
57     p = head;
58     while(p->next!=NULL){
59         p2=head2->next;
60         while(p2!=NULL){
61             if(p->next->num==p2->num){
62                 break;
63             }
64             p2 = p2->next;
65         }
66         if(p2==NULL){    //没有找到
67             Node* q = new Node;
68             q = p->next;    //存储一会要销毁的空间地址
69             p->next=p->next->next;
70             delete(q);    //销毁删掉的节点
71         }
72         else    //找到了
73             p=p->next;
74     }
75 
76     //输出
77     p=head->next;
78     while(p!=NULL){
79         cout<<p->num<<' ';
80         p=p->next;
81     }
82     cout<<endl;
83     /*
84     p=head2->next;
85     while(p!=NULL){
86         cout<<p->num<<endl;
87         p=p->next;
88     }
89     */
90     return 0;
91 }

 

Freecode : www.cnblogs.com/yym2013

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值