summaryrefslogtreecommitdiff
path: root/reverse-list.cpp
blob: f5040afc2dbee3d2a26e2a3f3ab12d8d15890333 (plain)
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

#include <cstdlib>
#include <iostream>

using namespace std;

struct node {
    const char* value;
    node* next;
};

void reverse(node*& start)
{
    if (!start)
        return;

    // Set the previous and current nodes.
    node* p0 = start;
    node* p1 = p0->next;
    p0->next = NULL;

    while (p1)
    {
        node* p2 = p1->next; // store the next node.
        p1->next = p0; // set the next of the current node to the previous node.

        // Update the previous and current nodes for the next iteration.
        p0 = p1;
        p1 = p2;
    }

    start = p0;
}

const char* strs[] = {
    "A", "B", "C", "D", "E", "F", 0
};

void populate(node*& start)
{
    // We assume the static string array is never empty.
    const char** p = strs;

    // Create the first node.
    node* first = new node;
    first->value = *p;
    first->next = NULL;

    node* cur = first;
    node* prev = NULL;
    for (++p; *p; ++p)
    {
        cur->next = new node;
        cur->next->value = *p;
        cur->next->next = NULL;

        prev = cur;
        cur = prev->next;
    }

    start = first;
}

void print(const node* start)
{
    for (const node* p = start; p; p = p->next)
        cout << p->value << " ";
    cout << endl;
}

int main()
{
    node* slist = NULL;
    populate(slist);
    cout << "input: ";
    print(slist);
    reverse(slist);
    cout << "output: ";
    print(slist);

    // TODO: De-allocate the list.
    return EXIT_SUCCESS;
}