-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathswap_nodes.c
58 lines (51 loc) · 1.12 KB
/
swap_nodes.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
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
static struct ListNode* swapPairs(struct ListNode* head)
{
if (head == NULL) {
return NULL;
}
struct ListNode dummy;
dummy.next = head;
struct ListNode *prev = &dummy;
struct ListNode *p = dummy.next;
while (p != NULL && p->next != NULL) {
struct ListNode *q = p->next;
/* deletion */
p->next = q->next;
/* insertion */
q->next = p;
prev->next = q;
/* iteration */
prev = p;
p = p->next;
}
return dummy.next;
}
int main(int argc, char **argv)
{
int i;
struct ListNode *p, *prev, dummy, *list;
dummy.next = NULL;
prev = &dummy;
for (i = 1; i < argc; i++) {
p = malloc(sizeof(*p));
int n = atoi(argv[i]);
printf("%d ", n);
p->val = n;
p->next = NULL;
prev->next = p;
prev = p;
}
putchar('\n');
list = swapPairs(dummy.next);
for (p = list; p != NULL; p = p->next) {
printf("%d ", p->val);
}
putchar('\n');
return 0;
}