-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.cc
129 lines (107 loc) · 2.06 KB
/
list.cc
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Singly linked list.
#include <utility>
#include <cstddef>
struct node {
int val;
node *next;
};
/* Print the values of the list L. */
static void
print_list (node *l)
{
while (l)
{
__builtin_printf ("%d%s", l->val, l->next ? " -> " : "");
l = l->next;
}
__builtin_printf ("\n");
}
/* Prepend a node with value VAL to the list HEAD. */
static void
prepend (node **head, int val)
{
*head = new node{val, *head};
}
/* Append a node with value VAL to the list HEAD. */
static void
append (node **head, int val)
{
node *l = new node{val, nullptr};
node **indirect = head;
while (*indirect)
indirect = &(*indirect)->next;
*indirect = l;
}
/* Reverse the list HEAD; modifies the links. */
static void
reverse (node **head)
{
node *prev = nullptr, *cur = *head;
while (cur)
{
node *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*head = prev;
}
/* Get the length of the LIST. */
static int
list_length (node *list)
{
int n = 0;
while (list)
++n, list = list->next;
return n;
}
/* Reverse the list LIST in place, i.e., without modifying the links. */
static void
reverse_in_place (node *list)
{
const int len = list_length (list);
if (len < 2)
return;
int pos = len - 1;
while (pos > 0)
{
// Swap list[cur] and list[cur + pos] values.
node *n = list;
// Advance N by POS.
for (size_t i = pos; i > 0; --i)
n = n->next;
std::swap (list->val, n->val);
pos -= 2;
list = list->next;
}
}
/* Free all the nodes of the list HEAD. */
static void
dispose (node **head)
{
while (*head)
{
node *cur = *head;
*head = (*head)->next;
delete cur;
}
}
int
main ()
{
node *l = nullptr;
prepend (&l, 4);
prepend (&l, 3);
prepend (&l, 2);
prepend (&l, 1);
append (&l, 5);
__builtin_printf ("initial:\n");
print_list (l);
__builtin_printf ("reversed:\n");
reverse (&l);
print_list (l);
__builtin_printf ("reversed in place:\n");
reverse_in_place (l);
print_list (l);
dispose (&l);
}