链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是在每一个节点(数据存储单元)里存放下一个节点的位置信息(即地址)。
"""
算法. 单链表示例:
"""
class SingleNode(object):
"""链表的节点类"""
def __init__(self, item):
# item 表示存放数据的元素
self.item = item
# next 下一个节点的标识(地址信息)
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self, head=None):
self.__head = head
def is_empty(self):
"""判断链表是否为空"""
return self.__head is None
def length(self):
"""获取链表⻓度"""
# cur初始时指向头节点
cur = self.__head
# count 表示链表的长度
count = 0
while cur is not None:
count += 1
# 将cur后移一个节点
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
# cur初始时指向头节点
cur = self.__head
while cur is not None:
# 打印节点的元素(数值)
print(cur.item, end=",")
cur = cur.next
print()
def add(self, item):
"""链表头部添加元素"""
# 创建添加的节点
node = SingleNode(item)
# 添加的节点下一个地址指向原来的头部节点地址
# 将新节点的链接域next指向头节点,即__head指向的位置
node.next = self.__head
# 将头节点指向添加的节点
self.__head = node
def append(self, item):
"""链表尾部添加元素"""
node = SingleNode(item)
# 先判断链表是否为空,如果是空则将__head指向新加的节点
if self.is_empty():
self.__head = node
# 若不为空,则找到尾部,将尾节点的next指向新节点
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素"""
# 如果pos小于或等于0,就相当于在头部添加节点
if pos <= 0:
self.add(item)
# 如果pos大于或等于链表的长度,就相当于在尾部添加节点
elif pos >= self.length():
self.append(item)
# 找到指定位置
else:
# cur = self.__head
# count相当于索引
node = SingleNode(item)
count = 0
# per用于指向指定位置pos的前一个位置pos-1,初始从头节点开始定位置
pre = self.__head
while count < (pos - 1):
count += 1
pre = pre.next
# 先将新节点node的next指向插入位置的节点
node.next = pre.next
# 将插入位置的前一个节点的next指向新节点node
pre.next = node
def remove(self, item):
"""删除节点"""
cur = self.__head
pre = None
while cur is not None:
# 找到这个元素
if cur.item == item:
# 第一个就是要删除的元素
if not pre:
# 将头节点指向删除节点的下一个节点位置
self.__head = cur.next
# 找到删除位置的上一个节点next指向删除位置的下一个节点位置
else:
pre.next = cur.next
break
else:
# 继续按链表后移节点
pre = cur
cur = cur.next
def search(self, item):
"""查找节点是否存在"""
cur = self.__head
while cur is not None:
if cur.item == item:
return True
cur = cur.next
return False
if __name__ == "__main__":
lb = SingleLinkList()
print(lb.is_empty())
lb.append(8)
lb.add(6)
lb.add(6)
lb.insert(2, 9)
lb.travel()
lb.add(3)
print(lb.length())
print(lb.search(5))
lb.remove(6)
lb.travel()
一种更复杂的链表是“双向链表”或“双面链表”。每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。
class Node(object):
"""双向链表节点"""
def __init__(self, item):
self.item = item
self.next = None
self.prev = None
class DLinkList(object):
"""双向链表"""
def __init__(self):
self.__head = None
def is_empty(self):
"""判断链表是否为空"""
return self.__head == None
def length(self):
"""返回链表的长度"""
cur = self.__head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历链表"""
cur = self.__head
while cur != None:
print cur.item,
cur = cur.next
print ""
def add(self, item):
"""头部插入元素"""
node = Node(item)
if self.is_empty():
# 如果是空链表,将_head指向node
self.__head = node
else:
# 将node的next指向_head的头节点
node.next = self.__head
# 将_head的头节点的prev指向node
self.__head.prev = node
# 将_head 指向node
self.__head = node
def append(self, item):
"""尾部插入元素"""
node = Node(item)
if self.is_empty():
# 如果是空链表,将_head指向node
self.__head = node
else:
# 移动到链表尾部
cur = self.__head
while cur.next != None:
cur = cur.next
# 将尾节点cur的next指向node
cur.next = node
# 将node的prev指向cur
node.prev = cur
def search(self, item):
"""查找元素是否存在"""
cur = self.__head
while cur != None:
if cur.item == item:
return True
cur = cur.next
return False
def insert(self, pos, item):
"""在指定位置添加节点"""
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
# 移动到指定位置的前一个位置
while count < (pos-1):
count += 1
cur = cur.next
# 将node的prev指向cur
node.prev = cur
# 将node的next指向cur的下一个节点
node.next = cur.next
# 将cur的下一个节点的prev指向node
cur.next.prev = node
# 将cur的next指向node
cur.next = node
def remove(self, item):
"""删除元素"""
cur = self.__head
while cur != None:
# 找到了要删除的元素
if cur.item == item:
# 先判断此结点是否是头节点
# 头节点
if cur == self.__head:
self.__head = cur.next
# 如果存在下一个结点,则设置下一个结点
if cur.next:
# 判断链表是否只有一个结点
cur.next.prev = None
else:
cur.prev.next = cur.next
# 如果存在下一个结点,则设置下一个结点
if cur.next:
cur.next.prev = cur.prev
break
else:
cur = cur.next
测试
if __name__ == "__main__":
ll = DLinkList()
ll.add(1)
ll.add(2)
ll.append(3)
ll.insert(2, 4)
ll.insert(4, 5)
ll.insert(0, 6)
print "length:",ll.length()
ll.travel()
print ll.search(3)
print ll.search(4)
ll.remove(1)
print "length:",ll.length()
ll.travel()
单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。
class Node(object):
"""节点"""
def __init__(self, item):
self.item = item
self.next = None
class SinCycLinkedlist(object):
"""单向循环链表"""
def __init__(self):
self.__head = None
def is_empty(self):
"""判断链表是否为空"""
return self.__head == None
def length(self):
"""返回链表的长度"""
# 如果链表为空,返回长度0
if self.is_empty():
return 0
count = 1
cur = self.__head
while cur.next != self.__head:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历链表"""
if self.is_empty():
return
cur = self.__head
print cur.item,
while cur.next != self.__head:
cur = cur.next
print cur.item,
print ""
def add(self, item):
"""头部添加节点"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = self.__head
else:
#添加的节点指向_head
node.next = self.__head
# 移到链表尾部,将尾部节点的next指向node
cur = self.__head
while cur.next != self.__head:
cur = cur.next
cur.next = node
#_head指向添加node的
self.__head = node
def append(self, item):
"""尾部添加节点"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = self.__head
else:
# 移到链表尾部
cur = self.__head
while cur.next != self.__head:
cur = cur.next
# 将尾节点指向node
cur.next = node
# 将node指向头节点_head
node.next = self.__head
def insert(self, pos, item):
"""在指定位置添加节点"""
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
# 移动到指定位置的前一个位置
while count < (pos-1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
"""删除一个节点"""
# 若链表为空,则直接返回
if self.is_empty():
return
# 将cur指向头节点
cur = self.__head
pre = None
while cur.next != self.__head:
if cur.item == item:
# 先判断此结点是否是头节点
if cur == self.__head:
# 头节点的情况
# 找尾节点
rear = self.__head
while rear.next != self.__head:
rear = rear.next
self.__head = cur.next
rear.next = self.__head
else:
# 中间节点
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# 退出循环,cur指向尾节点
if cur.item == item:
if cur == self.__head:
# 链表只有一个节点
self.__head = None
else:
# pre.next = cur.next
pre.next = self.__head
def search(self, item):
"""查找节点是否存在"""
if self.is_empty():
return False
cur = self.__head
if cur.item == item:
return True
while cur.next != self.__head:
cur = cur.next
if cur.item == item:
return True
return False
if __name__ == "__main__":
ll = SinCycLinkedlist()
ll.add(1)
ll.add(2)
ll.append(3)
ll.insert(2, 4)
ll.insert(4, 5)
ll.insert(0, 6)
print "length:",ll.length()
ll.travel()
print ll.search(3)
print ll.search(7)
ll.remove(1)
print "length:",ll.length()
ll.travel()