forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.c
65 lines (55 loc) · 1.25 KB
/
24.c
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
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* swapPairs(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head;
struct ListNode *p = head;
struct ListNode *q = head->next;
struct ListNode *new_head = q;
struct ListNode *t = NULL;
while (p && q) {
t = q->next;
q->next = p;
if (t && t->next) {
p->next = t->next;
}
else {
p->next = t;
break;
}
p = t;
q = p->next;
}
return new_head;
}
int main() {
int n = 5;
struct ListNode *head = (struct ListNode *)calloc(n, sizeof(struct ListNode));
struct ListNode *p = head;
int i;
for (i = 0; i < n - 1; i++) {
p->val = i + 1;
p->next = p + 1;
p = p->next;
}
p->val = n;
p->next = NULL;
printf("Linked List: ");
p = head;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
p = swapPairs(head);
printf("Swap Pairs: ");
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}