-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomPartin2sortedList.cpp
More file actions
80 lines (67 loc) · 1.55 KB
/
Copy pathcomPartin2sortedList.cpp
File metadata and controls
80 lines (67 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*打印两个有序链表的公共部分:
给定两个有序链表的头指针head1 head2打印它们的公共部分
思路:如果head1<head2 head1向下移动
如果head1>head2,head2向下移动
如果head1==head2,head1 head2均向下移动
*/
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// TODO:此处用的是自己定义的链表节点,可以直接使用c++提供的list结构来实现
typedef struct ListNode{
int value;
ListNode * next;
ListNode(int value){
this->value = value;
this->next = nullptr;
}
}listNode;
void printcommonIn2List(ListNode* head1, listNode* head2){
listNode* p1 = head1;
listNode* p2 = head2;
while (p1 != NULL && p2 != NULL){
if (p1->value < p2->value){
p1 = p1->next;
}
else if (p1->value > p2->value){
p2 = p2->next;
}
else{
cout << p1->value << " ";
p1 = p1->next;
p2 = p2->next;
}
}
}
int main(){
// 创建链表
listNode* head1 = new listNode(2);//创建节点并偏移
listNode* head2 = new listNode(2);
listNode* p = head1;// 记录头结点
listNode* q = head2;// 记录头结点
for (int i = 0; i < 14; i++){
p->next = (new listNode(i));
p = p->next;
q->next = (new listNode(i*2));
q = q->next;
}
cout << "head1: ";
p = head1;
while (p != NULL){
cout << p->value << " ";
p = p->next;
}
cout << endl;
cout << "head2: ";
q = head2;
while (q != NULL){
cout << q->value << " ";
q = q->next;
}
cout << endl;
cout << "common number: ";
printcommonIn2List(head1, head2);
system("pause");
return 0;
}