链表
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 相比于线性表顺序结构,操作复杂。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。
基本操作
class Node(object):
"""
封装节点
"""
def __init__(self, item):
# 存储数据元素的数据域
self.item = item
# 存储下一个结点地址的指针域
self.next = None
class Link(object):
"""
封装链表
"""
def __init__(self):
# 初始化一个空链表
self._head = None
# '_head' 用于指向链表的第一个节点
def add(self, item):
"""
链表首部插入节点
:param item:
:return:
"""
node = Node(item)
node.next = self._head
self._head = node
def travel(self):
"""
遍历每一个节点
:return:
"""
cur = self._head
while cur:
print(cur.item)
cur = cur.next
def length(self):
"""
链表中节点的个数
:return:
"""
count_node = 0
cur = self._head
while cur:
count_node += 1
cur = cur.next
return count_node
def isEmpty(self):
"""
判断链表是否为空
:return:
"""
return self._head == None
def search(self, item):
"""
查找是否存在item对应的节点
:param item:
:return:
"""
find = False
cur = self._head
while cur:
if cur.item == item:
find = True
break
else:
cur = cur.next
return find
def append(self, item):
"""
链表的尾部插入节点
:param item:
:return:
"""
node = Node(item)
if self._head == None:
self._head = node
return
cur = self._head
pre = None
while cur:
pre = cur
cur = cur.next
pre.next = node
def insert(self, pos, item):
"""
链表中指定的位置插入新的节点
:param pos:
:param item:
:return:
"""
node = Node(item)
if pos == 0:
node.next = self._head
self._head = node
return
pre = None
cur = self._head
for i in range(pos):
pre = cur
cur = cur.next
pre.next = node
node.next = cur
def remove(self, item):
"""
删除节点
:param item:
:return:
"""
cur = self._head
pre = None
if cur.item == item:
self._head = cur.next
return
while True:
pre = cur
cur = cur.next
if cur.item == item:
pre.next = cur.next
break
if cur == None:
break
def reverse(self):
"""
链表倒置
:return:
"""
pre = None
cur = self._head
next_node = cur.next
while cur:
cur.next = pre
pre = cur
cur = next_node
if cur != None:
next_node = next_node.next
self._head = pre
self.travel()
if __name__ == '__main__':
link = Link()
link.append(1)
link.append(2)
link.append(3)
link.append(4)
link.reverse()
# 4
# 3
# 2
# 1