一方向非循環チェーンテーブル(作成、遍歴、増加、削除、検索、空判定)


# coding: utf-8


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


#        
class LinkList(object):
    def __init__(self):
        self._head = None

    def is_empty(self):
        #         
        return self._head is None

    def length(self):
        #     
        num = 0
        cur = self._head
        while cur is not None:
            num += 1
            cur = cur.next
        return num

    def travel(self):
        #     
        cur = self._head
        while cur is not None:
            print(cur.item, end=' ')
            cur = cur.next
        print('length:', self.length())

    def add(self, item):
        #   
        node = Node(item)
        node.next = self._head
        self._head = node

    def append(self, item):
        #   
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next is not None:
                cur = cur.next
            cur.next = node

    def insert(self, pos, item):
        #  pos   
        if pos <= 0:
            self.add(item)
        elif pos >= self.length():
            self.append(item)
        else:
            node = Node(item)
            cur = self._head
            pos_cur = 0
            while pos_cur + 1 != pos:
                cur = cur.next
                pos_cur += 1
            node.next = cur.next
            cur.next = node

    def remove(self, item):
        #        item       
        if self.is_empty():
            return 'List is empty.'
        cur = self._head
        if cur.item == item:
            self._head = cur.next
        else:
            while cur.next is not None and cur.next.item != item:
                cur = cur.next
            if cur.next.item == item:
                cur.next = cur.next.next

    def search(self, item):
        #     item      
        cur = self._head
        while cur is not None:
            if cur.item == item:
                return True
            else:
                cur = cur.next
        return False


if __name__ == '__main__':
    a = LinkList()
    a.travel()
    a.append(1)
    a.travel()
    a.append(2)
    a.travel()
    a.add(3)
    a.travel()
    a.append(100)
    a.travel()
    a.insert(1, 600)
    a.travel()
    a.insert(0, 700)
    a.travel()
    a.insert(6, 1314)
    a.travel()
    a.insert(6, 520)
    a.travel()
    a.remove(1)
    a.travel()
    a.remove(1314)
    a.travel()
    a.remove(700)
    a.travel()
    print(a.search(100))
    print(a.search(1314))