상세 컨텐츠

본문 제목

(Python) Linked List

Python/Concept

by 코딩하는 낙타 2020. 2. 24. 17:12

본문

 

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
# Node 클래스 정의
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
 
# LinkedList 클래스 (자료구조 정의)
class LinkedList:
    # 초기화 메소드
    def __init__(self):
        dummy = Node("dummy")
        self.head = dummy
        self.tail = dummy
 
        self.current = None
        self.before = None
 
        self.num_of_data = 0
 
    # append 메소드 (insert - 맨 뒤에 노드 추가, tail과 node의 next, 데이터 개수 변경)
    def append(self, data):
        new_node = Node(data)
        self.tail.next = new_node
        self.tail = new_node
 
        self.num_of_data += 1
 
    # delete 메소드 (delete - current 노드 삭제, 인접 노드의 current, next 변경, 데이터 개수 변경)
    def delete(self):
        pop_data = self.current.data
 
        if self.current is self.tail:
            self.tail = self.before
 
        self.before.next = self.current.next
        self.current = self.before  # 중요 : current가 next가 아닌 before로 변경된다.
 
        self.num_of_data -= 1
 
        return pop_data
 
    # first 메소드 (search1 - 맨 앞의 노드 검색, before, current 변경)
    def first(self):
        if self.num_of_data == 0:
            return None
 
        self.before = self.head
        self.current = self.head.next
 
        return self.current.data
 
 
    # next 메소드 (search2 - current 노드의 다음 노드 검색, 이전에 first 메소드가 한번은 실행되어야 함)
    def next(self):
        if self.current.next == None:
            return None
 
        self.before = self.current
        self.current = self.current.next
 
        return self.current.data
 
    def size(self):
        return self.num_of_data
 
 
LList = LinkedList()
LList.append(1)
LList.append(2)
LList.append(3)
LList.append(4)
# LList = ["dummy", 1, 2, 3, 4] 와 같은 모습을 상상하면 된다.
 
print('first :', LList.first())         # first : 1
print('second :', LList.next())         # second : 2
print('third :', LList.next())          # third : 3
print('tail :', LList.next())           # tail : 4
print('size :', LList.size())           # size : 4
LList.first()
LList.next()
print('current:', LList.current.data)   # current: 2 (first로 간 다음 next로 한 번 이동하였으므로 두 번째 값)
print('pop_data :', LList.delete())     # pop_data : 2
print('current:', LList.current.data)   # current: 1 (delete 메소드 사용 후 탐색 위치는 삭제한 노드 바로 앞)
print('size :', LList.size())           # size : 3 (노드 하나를 삭제했으므로 size는 3)
 

 

관련글 더보기

댓글 영역