포시코딩

2월20일 - Linked List 구현 심화 (Python) 본문

TIL

2월20일 - Linked List 구현 심화 (Python)

포시 2023. 2. 20. 12:32
728x90

Linked List - Class 활용해 구현

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):
        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 search(self, data):
        node = self.head
        if node == None:
            return False
        while node:
            if node.data == data:
                return node.data
            else:
                node = node.next
        return False


test = NodeMGMT(0)
for i in range(1, 10):
    test.add(i)
test.desc()
print('search: ', test.search(4))
print('search: ', test.search(15))

 

Double Linked List

class Node:
    def __init__(self, data, next=None, prev=None):
        self.data = data
        self.next = next
        self.prev = prev
    
class NodeMGMT:
    def __init__(self, data):
        self.head = Node(data)
        self.tail = self.head
    
    def add(self, data):
        node = self.head
        while node.next:
            node = node.next
        temp = Node(data)
        node.next = temp
        temp.prev = node
        self.tail = temp
    
    def desc(self):
        temp = []
        node = self.head
        while node:
            # print(node.data)
            temp.append(node.data)
            node = node.next
        print('desc: ', *temp)

    def desc_reverse(self):
        temp = []
        node = self.tail
        while node:
            # print(node.data)
            temp.append(node.data)
            node = node.prev
        print('desc_reverse: ', *temp)

    def search_from_head(self, data):
        node = self.head
        if node == None:
            return False
        while node:
            if node.data == data:
                return node.data
            else:
                node = node.next
        return False
    
    def search_from_tail(self, data):
        node = self.tail
        if node == None:
            return False
        while node:
            if node.data == data:
                return node.data
            else:
                node = node.prev
        return False


test = NodeMGMT(0)
for i in range(1, 10):
    test.add(i)

test.desc()
test.desc_reverse()

print('search_from_head: ', test.search_from_head(4))
print('search_from_head: ', test.search_from_head(7))
print('search_from_head: ', test.search_from_head(15))

print('search_from_tail: ', test.search_from_tail(4))
print('search_from_tail: ', test.search_from_tail(7))
print('search_from_tail: ', test.search_from_tail(15))
728x90