概念:链表是通过一个个节点组成的,每个节点都包含了称为cargo的基本单元,它也是一种**递归**的数据结构。
和C不一样的是python没有专门的指针概念,在python中每个变量都是指针
链表的删除可以通过修改指针
来实现
Python实现链表的方法:
class Node:
'''
data:节点保存的数据
_next:保存下一个节点对象
'''
def __init__(self,data,pnext=None):
self.data=data
self._next=pnext
1.节点,每一个节点有两个域:
左:值域,右:针域
2.head节点:特殊节点,永远指向第一个节点
3.tail节点:特殊节点,永远指向最后一个节点
4.None:链表最后节点的针域的指针指向None值,因此也叫接地点.
class Node:
def __init__(self,data = None, next = None):
self.data = data
self.next = next
创建独立节点:
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
表示节点间关系:
node1.next = node2
node2.next = node3
LinkedList() 创建空链表,不需要参数,返回值是空链表
is_empty() 测试链表是否为空,不需要参数,返回值是布尔值
append(data) 在尾部增加一个元素作为列表最后一个,参数是要追加的元素,无返回值
iter() 遍历链表,无参数,无返回值,此方法一般是一个生成器
insert(idx,value) 插入一个元素,参数为插入元素的索引和值
remove(idx)移除1个元素,参数为要移除的元素或索引,并修改链表
size() 返回链表的元素数,不需要参数,返回值是个整数
search(item) 查找链表某元素,参数为要查找的元素或索引,返回是布尔值
链表是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)。
两种最简单的链表为单向链表和双向链表。
单向链表通过一个外部的头链接来访问第1项,单向链表的节点被分成两个部分,第一部分保存或显示关于节点的信息,第二部分储存下一节点地址。
单向链表只能向一个方向遍历。单向链表中每个节点只有一个指针。
单向链表结构图:
双向链表结构图:
链表的基本操作:遍历next节点
probe = head
while probe != None:
probe = probe.next
注意:
不可以用head来遍历列表,否则会丢失列表的一些节点,可以使用和head相同类型的临时的指针变量,这个变量先初始化为链表结构的head指针,然后控制一个循环。
单向链表遍历为例,流程框图如下:
遍历结束后,temp指针为None,而head指针还是指向第一个节点,遍历在时间上是线性的,并且不需要额外的内存。
遍历单链表结构会访问每一个节点,并且当遇到一个空链接的时候终止,而None就是充当负责停止这个过程的哨兵。
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def append(self,data):
node = Node(data)
if self.head is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def iter(self):
if not self.head:
return
cur = self.head
yield cur.data
while cur.next:
cur =cur.next
yield cur.data
def insert(self, idx, value):
cur = self.head
cur_idx = 0
if cur is None:
raise Exception("The list is an empty")
while cur_idx < idx - 1:
cur = cur.next
if cur is None:
raise Exception('......')
cur_idx = cur_idx + 1
node = Node(value)
node.next = cur.next
cur.next = node
if node.next is None:
self.tail = node
def remove(self, idx):
cur = self.head
cur_idx = 0
if self.head is None: # 空链表时
raise Exception('The list is an empty list')
while cur_idx < idx-1:
cur = cur.next
if cur is None:
raise Exception('list length less than index')
cur_idx += 1
if idx == 0: # 当删除第一个节点时
self.head = cur.next
cur = cur.next
return
if self.head is self.tail: # 当只有一个节点的链表时
self.head = None
self.tail = None
return
cur.next = cur.next.next
if cur.next is None: # 当删除的节点是链表最后一个节点时
self.tail = cur
def size(self):
current = self.head
count = 0
if current is None:
return 'The list is an empty list'
while current is not None:
count += 1
current = current.next
return count
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.data == item:
found = True
else:
current = current.next
return found
验证操作:
if __name__ == '__main__':
link_list = LinkedList()
for i in range(150):
link_list.append(i)
print(link_list.is_empty())
link_list.insert(10, 30)