forked from embedded2016/unit-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap.c
88 lines (73 loc) · 2.04 KB
/
swap.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
typedef struct List_node {
int value;
struct List_node *next;
} List_node;
typedef struct List_node List;
List *swap(List *head, List *node_1, List *node_2)
{
if (!head &&
(node_1 == NULL) && (node_2 == NULL) &&
(node_1 == node_2))
return head;
int num_pre_node_1_and_node_2 = 0;
List *_head = head;
List *pre_node_1,*pre_node_2,*tmp_node;
while (head && head->next) {
if (head->next == node_1) {
pre_node_1 = head;
num_pre_node_1_and_node_2 = num_pre_node_1_and_node_2 + 1;
}
if (head->next == node_2) {
pre_node_2 = head;
num_pre_node_1_and_node_2 = num_pre_node_1_and_node_2 + 1;
}
head = head->next;
}
head = _head;
if (head == node_1) {
pre_node_1 = NULL;
num_pre_node_1_and_node_2 = num_pre_node_1_and_node_2 + 1;
}
if (head == node_2) {
pre_node_2 = NULL;
num_pre_node_1_and_node_2 = num_pre_node_1_and_node_2 + 1;
}
if (num_pre_node_1_and_node_2 != 2)
return head;
if (pre_node_1 == NULL) {
pre_node_2->next = node_1;
tmp_node = node_1->next;
node_1->next = node_2->next;
node_2->next = tmp_node;
return node_2;
}
if (pre_node_2 == NULL) {
pre_node_1->next = node_2;
tmp_node = node_2->next;
node_2->next = node_1->next;
node_1->next = tmp_node;
return node_1;
}
if (node_2->next == node_1) {
pre_node_2->next = node_1;
tmp_node = node_1->next;
node_1->next = node_2;
node_2->next = tmp_node;
return head;
}
if (node_1->next == node_2) {
pre_node_1->next = node_2;
tmp_node = node_2->next;
node_2->next = node_1;
node_1->next = tmp_node;
return head;
}
pre_node_1->next = node_2;
tmp_node = node_2->next;
node_2->next = node_1->next;
pre_node_2->next = node_1;
node_1->next = tmp_node;
return head;
}