标签:python val 线性表 操作 线性 self one 表的基本操作 test
上文笔者描述了单链表的基本操作,但尾插法在单链表中效率太低,我们可以对单链表进行简单的变形,提高尾端插入元素等操作的效率。
单向循环链表只需要将普通的单链表首尾相连即可实现。
Python实现:
class ListNode():
def __init__(self, val, next=None):
self.val = val
self.next = next
class OneWayCircularLinkedList():
def __init__(self):
self.head = None
# 在链表头部插入元素
def prepend(self, val):
# 若头部结点为空,那么头尾结点相同
node = ListNode(val)
if not self.head:
self.head = node
self.head.next = self.head
else:
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = node
node.next = self.head
# 在链表尾部插入元素
def append(self, val):
if not self.head:
self.head = ListNode(val)
self.head.next = self.head
else:
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = ListNode(val, self.head)
# 计算链表长度
def get_length(self):
if not self.head:
return 0
cur = self.head
length = 1
while cur.next != self.head:
length += 1
cur = cur.next
return length
# 弹出尾部元素
def pop_last(self):
if not self.head:
raise ValueError(‘self.head 必须非空‘)
if self.head.next == self.head:
return self.head.val
cur = self.head
while cur.next.next != self.head:
cur = cur.next
rear = cur.next.val
cur.next = cur.next.next
return rear
if __name__ == ‘__main__‘:
def testfunction(node):
nums = []
cur = node
while cur.next != node:
nums.append(cur.val)
cur = cur.next
nums.append(cur.val)
return nums
sample = OneWayCircularLinkedList()
for i in range(8):
sample.prepend(i)
print(testfunction(sample.head))
sample.append(2)
print(testfunction(sample.head))
print(sample.get_length())
print(sample.pop_last())
不难发现,单向循环链表的优势在于头尾相连,此时尾端插入的效率较高。
标签:python val 线性表 操作 线性 self one 表的基本操作 test
原文地址:https://www.cnblogs.com/yiwen-statistics/p/13795733.html