그 외 공부/Algorithm

# 2_DLL(Doubly Linked List)

ssangeun 2017. 11. 5. 17:28

 

 

# The source code

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
130
131
132
133
134
135
136
#include<stdio.h>
#include<stdlib.h>
 
struct node {
    int i;
    struct node * prev;
    struct node * next;
};
struct node * head = 0;
void addDLL(int v)
{
    struct node * cur = (struct node *)malloc(sizeof(struct node));
    cur->= v;
    cur->next = 0;
    cur->prev = 0;
 
    if (head == 0)
    {
        head = cur;
        return;
    }
    else
    {
        struct node *tmp = head;
 
        while (tmp->next != 0)
        {
            tmp = tmp->next;
        }
        tmp->next = cur;
        cur->prev = tmp;
        return;
    }
}
void delDLL(int v)
{
    struct node *tmp = head;
    struct node *cur = 0;
 
    if (head->== v)
    {
        tmp = head;
 
        head = tmp->next;
        free(tmp);
        return;
    }
 
    while (tmp != 0)
    {
        if (tmp->== v)
        {
            cur = tmp->prev;
            cur->next = tmp->next;
            if (tmp->next != 0)
            {
                tmp->next->prev = cur;
            }
            free(tmp);
            break;
        }
        tmp = tmp->next;
    }
    return;
}
void destroyDLL()
{
    struct node *tmp = head;
    struct node *cur = tmp;
    while (head != 0)
    {
        tmp = head;
        head = tmp->next;
        free(tmp);
    }
}
void insertDLL(int v1, int v2)
{
    struct node * tmp = head;
    struct node * newone = (struct node *)malloc(sizeof(struct node));
    newone->= v2;
    newone->next = 0;
    newone->prev = 0;
 
    while (tmp != 0)
    {
        if (tmp->== v1)
        {
            newone->next = tmp->next;
            newone->prev = tmp;
            tmp->next = newone;
            if (newone->next != 0)
            {
                newone->next->prev = newone;
            }
            break;
        }
        tmp = tmp->next;
    }
    return;
}
void printDLL()
{
    struct node * cur = head;
 
    while (cur != 0)
    {
        printf("%d, ", cur->i);
        cur = cur->next;
    }
    return;
}
void main(void)
{
    addDLL(1);
    addDLL(2);
    addDLL(3);
    printf("DLL after adding 1,2,3 :");
    printDLL();
 
    destroyDLL();
 
    addDLL(4);
    addDLL(5);
    addDLL(6);
    printf("\nDLL after destroying 1,2,3 and adding 4,5,6 :");
    printDLL();
 
    insertDLL(610);
    printf("\nDLL after inserting 6 in front of 10 :");
    printDLL();
 
    delDLL(6);
    printf("\nDLL after deleting 6 :");
    printDLL();
}
cs

 

 

 

# The result