顺序表 | 链表 |
---|---|
List(数组) | 单链表<->双链表 |
一:顺序表,查询速度快,但是增加删除数据慢。
二:链表:查询慢,修改数据快
# 单链表
# 单链表
class Node:
"""
单链表节点
:return:
"""
def __init__(self, data):
self.data = data # 数据域
self.next = None # 指针域
class SingleLinkList:
"""单链表"""
def __init__(self, node=None):
node = Node(node)
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:
cur = cur.next
count += 1
return count
def travel(self):
cur = self._head
while cur is not None:
print("cur is: %s" % cur.data)
cur = cur.next
def add(self, item, index):
print(self.length())
if index <= 0:
# 在头部添加。
node = Node(item)
node.next = self._head
self._head = node
elif index >= self.length():
# 在尾部添加。
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
else:
# 在中间位置添加。
node = Node(item)
cur = self._head
count = 0
while cur is not None:
count += 1
if count == index:
node.next = cur.next
cur.next = node
break
def delete(self, item):
cur = self._head
pre = None
while cur is not None:
if cur.data == item:
if cur == self._head:
self._head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def modity(self, index, item):
cur = self._head
count = 0
while cur is not None:
if count == index:
cur.data = item
break
cur = cur.next
count += 1
def search(self, item):
cur = self._head
while cur is not None:
if cur.data == item:
return True
else:
return False
if __name__ == '__main__':
link_list = SingleLinkList(15) # 初始化一个数据
link_list.add(1, 0) # 开头插入一条数据
link_list.add(3, 2) # 在末尾添加一个条数据
link_list.add(4, 2)
link_list.add(2, 8) # 末尾添加一条数据
link_list.travel()