카테고리 없음

linked list

fw93 2018. 3. 19. 14:19
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
#include "stdafx.h"
#include <cstdio>
#include <iostream>
 
using namespace std;
 
template<class T>
class node {
public:
    T data;
    node * next;
    node(T da);
};
 
template<class T>
node<T>::node(T da) {
    data = da;
    next = NULL;
}
 
template<class T>
class linkedlist {
private:
    node<T> * head;
    int size;
public:
    linkedlist();
    void append(T da);
    T remove();
    void print();
};
 
template<class T>
linkedlist<T>::linkedlist() {
    head = NULL;
    size = 0;
}
 
template<class T>
void linkedlist<T>::append(T da){
    if (size == 0) {
        node<T> * tmp = new node<T>(da);
        head = tmp;
        size++;
        return;
    }
    node<T> * curr = head;
    while (curr->next != NULL) {
        curr = curr->next;
    }
    node<T> *tmp = new node<T>(da);
    curr->next = tmp;
    size++;
    return;
}
 
template<class T>
T linkedlist<T>::remove() {
    if (size == 0) {
        printf("no elements to delete\n");
        return head->data;
    }
    if (size == 1) {
        head = NULL;
        size = 0;
    }
    node<T> * curr = head;
    for (int i = 0; i < size-2; i++) {
        curr = curr->next;
    }
    T ret = curr->next->data;
    curr->next = NULL;
    size--;
    return ret;
}
 
template<class T>
void linkedlist<T>::print() {
    if (size == 0) {
        printf("empty linkedlist\n");
        return;
    }
    else {
        node<T> * curr = head;
        while (1) {
            printf("%d ", curr->data);
            if (curr->next == NULL) {
                break;
            }
            curr = curr->next;
        }
        printf("\n");
    }
}
 
int main() {
    linkedlist<int> ll;
    ll.append(1);
    ll.append(2);
    ll.append(3);
    ll.remove();
    ll.print();
    while (1) {}
    return 0;
}
 
 
 
 
cs