File size: 1,213 Bytes
4559903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>
#include "list.h"

#define N 10

struct list *list_reverse(struct list *head)
{
    struct list *rev_head = NULL;
    struct list *rev_cur = NULL;
    struct list *cur = head;

    do 
    {
        rev_cur = (struct list *) malloc( sizeof(struct list) );
        rev_cur->n = cur->n;
        rev_cur->next = rev_head;
        rev_head = rev_cur;

    } while( cur = cur->next );

    return rev_head;
}

void list_reverse_inplace(struct list **head)
{
    struct list *rev;
    struct list *cur;
    struct list *tmp;
    
    cur = *head;
    rev = NULL;
    while( cur )
    {
        tmp = cur->next;
        cur->next = rev;
        rev = cur;
        cur = tmp;
    }

    *head = rev;
}

int main(int argc, const char *argv[])
{
    struct list *head, *rev, *rev2;

    head = list_constructor_tail(N);
    printf("Original list\n");
    list_print(head);
    printf("-----------------------------\n");

    rev = list_reverse(head);
    printf("Reverted list\n");
    list_print(rev);
    list_print(head);
    printf("-----------------------------\n");

    list_reverse_inplace(&head);
    printf("Inplace Reverted list\n");
    list_print(head);

    return 0;
}