본문 바로가기
  • 紹睿: 자유롭고 더불어 사는 가치있는 삶
Data/python·알고리즘

[Linked list] Linked list 코드

by 징여 2018. 9. 24.
반응형

linked list


linked list는 이런 노드가 연결 되어있다.

class Node:
    def __init__(self, item):
        self.val = item
        self.next = None

class LinkedList:
    def __init__(self, item):
        self.head = Node(item)

    def add(self, item):
        cur = self.head
        while cur.next != None:
            cur = cur.next
        cur.next = Node(item)

    def remove(self, item):
        if self.head.val == item:
            self.head = self.head.next
        else:
            cur = self.head
            while cur.next != None:
                if cur.next == item:
                    self._remove(item)
                    return
                cur = cur.next

    def _remove(self, item):
        cur = self.head
        while cur.next != None:
            if cur.next.val == item:
                nextnode = cur.next.next
                cur.next = nextnode
                break
    def reverse(self):
        prev = None
        cur = self.head
        while cur != None:
            next = cur.next
            cur.next = prev
            prev = cur
            cur = next
        self.head = prev

    def print(self):
        cur = self.head
        link = []
        while cur != None:
            link.append(cur.val)
            cur = cur.next
        print(link)



 

 

반응형

댓글