单链表
class Node():
"""节点"""
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkList ():
"""单链表"""
def __init__(self, node=None):
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self):
"""链表长度"""
cur = self.__head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
count = 0
while cur is not None:
print(cur.elem, end=' ')
cur = cur.next
print(' ')
return count
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):
"""指定位置添加元素
:param pos: 从0开始
:param item:
先改变新节点的next区域,保证原有链表的所有节点关系不打断
"""
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
count = 0
pre = self.__head
while count < (pos-1):
count += 1
pre = pre.next
node.next = pre.next
pre.