티스토리 뷰

반응형

연결리스트에 새로운 데이터 추가하기

 

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
class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next
    
class NodeMgmt:
    def __init__(self, data):
        self.head = Node(data)
    
    def add(self, data):
        if self.head == '':
            self.head = Node(data)
        else:
            node = self.head
            while node.next:
                node = node.next
            node.next = Node(data)
    
    def desc(self):
        node = self.head
        while node:
            print(node.data)
            node = node.next
    
    def delete(self,data):
        if self.head == '':
            print("data가 없습니다.")
            return
 
        if self.head.data == data:
            temp = self.head
            self.head = self.head.next
            del temp
        else# node의 head가 아닌 값을 삭제할 경우
            node = self.head
            # node의 다음값이 존재하는 동안
            while node.next:
                if node.next.data == data:
                    temp = node.next
                    node.next = temp.next
                    del temp
                else:
                    node = node.next
            
cs

 

 

 

반응형
댓글