1. 程式人生 > >python 實現單鏈表

python 實現單鏈表

# -*- coding:utf-8 -*-

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


class LinkedList(object):
    def __init__(self, maxsize=None):
        self.maxsize = maxsize
        self.root = Node()  # 定義一個根節點
        self.length = 0
        self.tailnode 
= None def __len__(self): return self.length # 呼叫的時候 len(self) = self.length def append(self, value): # 實現尾插法 if self.maxsize is not None and len(self) > self.maxsize: # self.length = len(self) raise Exception('Full') node = Node(value) # 定義一個新節點
tailnode = self.tailnode # 取一下尾結點 if tailnode is None: # 如果尾結點為空,則表明只有一個root結點 self.root.next = node # root結點直接連結新建立的結點 else: tailnode.next = node # 否則 尾結點的下一結點為新建立的結點 self.tailnode = node # 更新尾結點 self.length += 1 # 長度加一 def
appendleft(self, value): headnode = self.root.next # headnode 相當於一個tmp, 只是暫時存下 self.root.next 的值 node = Node(value) self.root.next = node node.next = headnode self.length += 1 def iter_node(self): curnode = self.root.next while curnode is not self.tailnode: # 每次執行yield 的時候 返回的事一個迭代值 yield curnode curnode = curnode.next yield curnode # 此時更新到了最後一個結點, 也要yield 出來 def __iter__(self): for node in self.iter_node(): yield node.value def remove(self, value): prevnode = self.root for curnode in self.iter_node(): if curnode.value == value: prevnode.next = curnode.next if curnode is self.tailnode: self.tailnode = prevnode del curnode self.length -= 1 return 1 else: prevnode = curnode # 這裡這麼寫是因為在下次迴圈的時候, curnode會遞增, 所以prevnode 是curnode的上一個node return -1 def find(self, value): index = 0 for node in self.iter_node(): if node.value == value: return index index += 1 return -1 def popleft(self): # 從左邊刪除結點 if self.root.next is None: raise Exception("pop from emptyLinkedList") headnode = self.root.next self.root.next = headnode.next self.length -= 1 value = headnode.value del headnode return value def clear(self): for node in self.iter_node(): del node self.root.next = None self.length = 0
# 下面是測試
def test_linklist(): ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.append(100) assert len(ll) == 4 assert ll.find(100) == 3 assert ll.find(231) == -1 ll.remove(100) assert len(ll) == 3 assert ll.find(100) == -1 assert list(ll) == [1, 2, 3] ll.appendleft(0) assert list(ll) == [0, 1, 2, 3] assert len(ll) == 4 headnode = ll.popleft() assert headnode == 0 assert len(ll) == 3 assert list(ll) == [1, 2, 3] ll.clear() len(ll) == 0 test_linklist()