文章目录
单链表
class Node(object):
"""节点"""
def __init__(self, elem):
self.elem = elem
self.next = None
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 = 1
while cur != None:
count += 1
cur = cur.next
return count
cur = self._head
while cur != None:
print(cur.elem)
cur = cur.next
def travel(self):
"""遍历整个链表"""
cur = self._head
while cur != None:
print(cur.elem, end="")
cur = cur.next
print("")
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 != None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素
:param pos 从0开始"""
if pos<= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
pre = self.__head
count = 0
while count < (pos-1):
count +=1
pre =pre.next
# 当循环退出后,pre指向pos-1位置
node = Node(item)
node.next = pre.next
pre.next = node
def remove(self, item):
"""删除节点"""
cur = self.__head
pre = None
while cur != None:
if cur.elem == item:
#先判断此节点是否为头节点
#头节点
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
else:
pre = cur
cur = cur.next
def search(self, item):
"""查找结点是否存在"""
cur = self.__head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
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.add(8)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.travel()
结果是:
True
1
False
2
8123456