공부기록

Linked List 본문

CS/Data Structure

Linked List

코타쿠 2021. 5. 31. 14:00

Linked List?

구현

python으로 구현한 코드는 아래와 같다.

class Node():
    def __init__(self, data, nextNode = None):
        self.data = data
        if nextNode == None or type(nextNode) == Node:
            self.nextNode = nextNode
        else:
            print("__init__ node type error :", type(Node))

    def getData(self):
        return self.data
    def setData(self, val):
        self.data = val
    def getNextNode(self):
        return self.nextNode
    def setNextNode(self, node):
        if type(node) == Node:
            self.nextNode = node
        else:
            print("setNextNode node type error:", type(Node))
    def __repr__(self):
        return "(data : " + str(self.data) + ")"


class LinkedList:
    def __init__ (self, head = None):
        self.head = head
        self.size = 0
    def getSize(self):
        return self.size
    def addNode(self, data):
        newNode = Node(data, self.head)
        self.head = newNode
        self.size += 1
    def printNodes(self):
        curr = self.head
        pos = 1
        while curr:
            print("position :" + str(pos) + " " + str(curr.data))
            pos += 1
            curr = curr.getNextNode()
    def insertNode(self, curr : Node, data):
        newNode = Node(data, curr)
        newNode.setNextNode(curr.getNextNode())
        curr.setNextNode(newNode)

    def removeNode(self, value):
        prev = None
        curr : Node = self.head
        while curr:
            if curr.getData() == value:
                if prev:
                    prev.setNextNode(curr.getNextNode())
                else:
                    self.head = curr.getNextNode()
                return True
            prev = curr
            curr = curr.getNextNode()
        return False

'CS > Data Structure' 카테고리의 다른 글

Red Black Trees  (0) 2021.10.27
Sorting  (0) 2021.05.30
Queue  (0) 2021.05.29
Linked List  (0) 2021.05.29
Stack  (0) 2021.05.29