본문 바로가기

일상/개인

스터디를 위한 링크드 리스트


※ 발코딩이라 오류가 있을 수 있습니다.


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
#include <cstdio>
#include <algorithm>
using namespace std;
struct Node {
    int data;
    char cdata;
    //... 원하는 자료형을 선언하면 됨
    Node* prev;
    Node* next;
    Node(int data, char cdata) :data(data), cdata(cdata) {
        prev = next = NULL;
    }
    Node() {}
};
struct DoublyLinkedList {
    int size;
    Node* head;
    Node* tail;
    DoublyLinkedList() {
        size = 0;
        head = tail = NULL;
    }
    void insert_head(int data,char cdata) {
        if (head == NULL) 
            head = tail = new Node(data, cdata);
        else {
            Node *newNode = new Node(data, cdata);
            newNode->next = head;
            head->prev = newNode;
            head = newNode;
        }
        size++;
    }
    void insert_tail(int data, char cdata) {
        if (tail == NULL) 
            head = tail = new Node(data, cdata);
        else {
            Node* newNode = new Node(data, cdata);
            newNode->prev = tail;
            tail->next = newNode;
            tail = newNode;
        }
        size++;
    }
    void delete_head() {
        if (!size) {
            puts("불가능합니다.");
            return;
        }
        printf("delete head : %d, %c\n", head->data, head->cdata);
        Node* tempNode = new Node;
        tempNode = head;
        head->next->prev = NULL;
        head = head->next;
        delete tempNode;
        size--;
    }
    void delete_tail() {
        if (!size) {
            puts("불가능합니다.");
            return;
        }
        printf("delete tail : %d, %c\n", tail->data, tail->cdata);
        Node* tempNode = new Node;
        tempNode = tail;
        tail->prev->next = NULL;
        tail = tail->prev;
        delete tempNode;
        size--;
    }
    void print() {
        Node* tempNode = new Node;
        tempNode = head;
        if (!size)puts("노드 없음");
        else {
            for (int i = 1; i <= size; i++) {
                printf("%d번째 노드 : %d, %c\n", i, tempNode->data, tempNode->cdata);
                tempNode = tempNode->next;
            }
        }
    }
};
int main() {
    DoublyLinkedList dll;
    dll.print();
    dll.delete_head();
    dll.insert_head(1'a');
    dll.insert_tail(2'b');
    dll.insert_tail(3'c');
    dll.insert_head(0'z');
    dll.print();
    dll.delete_tail();
    dll.delete_head();
    dll.print();
    return 0;
}
 
cs



'일상 > 개인' 카테고리의 다른 글

SPFA에서 음수 사이클을 확인하는 방법  (0) 2017.07.07