-
Notifications
You must be signed in to change notification settings - Fork 0
/
test08.cpp
80 lines (71 loc) · 1.44 KB
/
test08.cpp
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
#include <queue>
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct Node {
int val;
Node* next;
Node(int val) : val(val), next(nullptr) {}
};
Node* createList(int n)
{
Node* head = new Node{ -1 },
* newNode{},
* p = head;
for (int i = 0; i < 10; i++)
{
newNode = new Node{ i * n };
p->next = newNode;
p = p->next;
}
newNode->next = head;
return head;
}
void printNode(Node* head)
{
Node* p = head;
do {
cout << p->val << ' ';
p = p->next;
} while (p != head);
cout << endl;
}
Node* merge(Node* a, Node* b) {
if (a == nullptr) return b;
if (b == nullptr) return a;
Node* dummy = new Node(0);
Node* cur = dummy;
Node* pa = a, * pb = b;
cur->next = pa;
cur = cur->next;
pa = pa->next;
cur->next = pb;
cur = cur->next;
pb = pb->next;
while (pa != a || pb != b) {
if (pa != a) {
cur->next = pa;
cur = cur->next;
pa = pa->next;
}
if (pb != b) {
cur->next = pb;
cur = cur->next;
pb = pb->next;
}
}
cur->next = dummy->next;
delete dummy;
return cur->next;
}
int main()
{
Node* list1= createList(1);
Node* list2= createList(2);
printNode(list1);
printNode(list2);
Node* list3 = merge(list1, list2);
printNode(list3);
}