-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path两个链表合并成不递减的链表.cpp
106 lines (95 loc) · 1.78 KB
/
两个链表合并成不递减的链表.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read();
void Print( List L ); /* empty node will return NULL */
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
/* your code */
List Merge(List L1, List L2)
{
List p, q, temp;
PtrToNode L = (PtrToNode)malloc(sizeof(struct Node));
L ->Next = NULL;
temp = L;
p = L1 ->Next;
q = L2 ->Next;
while(q && p)
{
if (p->Data < q->Data)
{
temp ->Next = p;
p = p ->Next;
temp = temp ->Next;
}
else
{
temp ->Next = q;
q = q ->Next;
temp = temp ->Next;
}
}
temp ->Next = NULL;
if (p)
temp ->Next = p;
if (q)
temp ->Next = q;
//output format need
L1 ->Next = NULL;
L2 ->Next = NULL;
return L;
}
List Read()
{
PtrToNode Begin,Last;
int num,val;
// inpit nums
scanf("%d",&num);
if (num == 0)
{
return NULL;
}
// convinent
Begin = (PtrToNode)malloc(sizeof(struct Node));
Begin -> Next = NULL;
Last = Begin;
while(num --)
{
scanf("%d", &val);
PtrToNode temp = (PtrToNode)malloc(sizeof(struct Node));
temp ->Next = NULL;
temp ->Data = val;
Last ->Next = temp;
Last = temp;
}
return Begin;
}
void Print( List L)
{
if (L->Next == NULL)
{
printf("NULL\n");
return;
}
while(L = L->Next)
{
printf("%d", L->Data);
}
putchar('\n');
}