【HBU】7-3 两个有序链表序列的交集 (20分)

清疚 2022-12-22 04:54 262阅读 0赞

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

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

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

输入样例:

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

输出样例:

  1. 2 5

将两个链表分别放进两个队列里,比较队首元素大小,如果相等则输出,再出队;如果不相等,将较大的那个元素出队,知道有一个队列为空结束

  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4. int main() {
  5. ios::sync_with_stdio(false);
  6. queue<int> a, b;
  7. int t;
  8. while(1){
  9. cin >> t;
  10. if(t == -1) break;
  11. a.push(t);
  12. }
  13. while(1){
  14. cin >> t;
  15. if(t == -1) break;
  16. b.push(t);
  17. }
  18. int num = 0;
  19. while(!a.empty() && !b.empty()){
  20. if(a.front() < b.front()) a.pop();
  21. else if(a.front() > b.front()) b.pop();
  22. else {
  23. if(num) cout << " ";
  24. cout << a.front();
  25. a.pop();
  26. b.pop();
  27. num++;
  28. }
  29. }
  30. if(num == 0) cout << "NULL";
  31. }

发表评论

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

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

相关阅读