# coding:utf-8
class Node(object):
"""節點0"""
def __init__(self, elem):
self.elem = elem
self.next = None
# node = None(100)
class SingleLinkList(object):
"""單鏈表"""
def __init__(self, node=None):
self._head = node
def is_empty(self):
"""鏈表是否爲空"""
return self._head == None
def length(self):
"""鏈表長度"""
# cur遊樸,用來移動遍歷節點
cur = self._head
# count記錄數量
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍歷整個鏈表"""
cur = self._head
while cur != None:
print(cur.elem)
cur = cur.next
def add(self, item):
"""鏈表頭部添加元素"""
pass
def append(self, item):
"""鏈表尾部添加元素"""
node = Node(item)
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素"""
pass
def remove(self, item):
"""刪除節點"""
pass
def search(self, item):
"""查找節點是否存在"""
pass
if __name__ == "__main__":
ll = SingleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
print(ll.is_empty())
print(ll.length())
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.travel()
代码实现效果