PAT 2-12 两个有序链表序列的交集(C语言实现)
来源:互联网 发布:中信银行客户端软件 编辑:程序博客网 时间:2024/04/30 00:47
题目描述:
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式说明:
输入分2行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式说明:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”。
样例输入与输出:
序号输入输出11 2 5 -12 4 5 8 10 -1
2 52
1 3 5 -12 4 6 8 10 -1
NULL3
1 2 3 4 5 -11 2 3 4 5 -1
1 2 3 4 54
3 5 7 -12 3 4 5 6 7 8 -1
3 5 75
-110 100 1000 -1
NULL
思路跟两个链表的合并差不多,唯一的区别是只有两个链表中元素相等时才将该元素插入到新表中。
源码:
#include<stdio.h>typedef struct node *ptrNode;typedef ptrNode LinkList; //头结点typedef ptrNode Position;//中间节点typedef int ElementType;struct node{ElementType Element;Position next;};int IsEmpty(LinkList L){return L->next == NULL;}LinkList creatList(void) {LinkList head,r,p;int x;head = (struct node*)malloc(sizeof(struct node)); //生成新结点r = head;scanf("%d",&x);while(x != -1){p = (struct node*)malloc(sizeof(struct node));p->Element = x;r->next = p;r = p;scanf("%d",&x);}r->next = NULL;return head;}LinkList intersectionList(LinkList a, LinkList b){Position ha, hb,hc;LinkList c,r,p;ha = a->next;hb = b->next;c = (struct node*)malloc(sizeof(struct node));r = c;while((ha != NULL)&&(hb != NULL)){p = (struct node*)malloc(sizeof(struct node));if(ha->Element < hb->Element){ha = ha->next;}else if(ha->Element > hb->Element){hb = hb->next;}else{p->Element = hb->Element;hb = hb->next;ha = ha->next;r->next = p; r = p;}}r->next = NULL;return c;}void printList(LinkList L){LinkList hc;int flag = 0;hc = L->next;if(hc == NULL)printf("NULL");while(hc != NULL){if(flag)printf(" ");elseflag = 1;printf("%d",hc->Element);hc = hc->next;}}int main(void){LinkList L1,L2,L3;L1 = creatList();L2 = creatList();L3 = intersectionList(L1,L2);printList(L3);return 0;}
0 0
- PAT 2-12 两个有序链表序列的交集(C语言实现)
- PAT 2-12. 两个有序链表序列的交集
- pat 2-12. 两个有序链表序列的交集
- PAT 2-11 两个有序链表序列的合并(C语言实现)
- 浙大PAT 2-12. 两个有序链表序列的交集 (解题思路)
- PAT 2-13 两个有序序列的中位数(C语言实现)
- 浙江大学PAT上机题解析之2-12. 两个有序链表序列的交集
- PAT DS 2-11 两个有序链表序列的交集
- 【C】两个有序链表序列的交集
- 两个有序链表序列的交集
- 2-12. 两个有序链表序列的交集
- 2-12. 两个有序链表序列的交集
- 7-2 两个有序链表序列的交集
- 7-2 两个有序链表序列的交集
- 两个有序链表序列的交集(20 分)
- 实验项目 2-12:两个有序链表序列的交集
- 《数据结构学习与实验指导》2-12:两个有序链表序列的交集
- 2-12. 两个有序链表序列的交集(20) (ZJU_PAT 链表 | vector)
- php Laravel框架学习(三) 之 路由
- TookKit-autohotkey_Simple automation of Windows and programs
- eclipse 的一些常用的快捷键。。。很有帮助。
- 序列最小优化算法
- Reverse Integer
- PAT 2-12 两个有序链表序列的交集(C语言实现)
- Appium测试安卓Launcher以滑动窗体获得目标应用
- IOS开源框架及他人经验
- HDU - 5008 Boring String Problem (后缀数组+二分+RMQ)
- poj1426 同余模定理+二叉树
- 大型网站系统架构的演化
- C语言、C++面试题(附答案)
- Leetcode: Unique Paths
- Android onTouchEvent, onClick及onLongClick的调用机制