class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def CreateList(self, nums):
head = tail = ListNode(-1) # 在链表中,有首节点、头节点的区别。头节点是指向链表的第一个元素,首节点是指向链表头节点的前一个元素,一般表示链表的开始。
for i in range(len(nums)):
newNode = ListNode(nums[i])
tail.next = newNode
tail = newNode
return head.next
def DeleteNode(self, head, num): # 删除值为 num 的链表节点
if head.val == num:
return head.next # 如果要删除的是头节点,直接返回head.next
pre, cur = head, head.next # 删除节点操作需要有指向当前节点的指针和指向当前节点前一个元素的指针。
while cur:
if cur.val == num: # 当前节点就是要找到的节点
pre.next = cur.next
cur.next = None
break
else: # 如果不是,就一直遍历下去,直到链表遍历结束
pre, cur = cur, cur.next
return head
def InsertNode(self, head, index, value): # 在指定位置插入节点,若大于链表长度,则返回-1,位置索引从 1 开始
# 要注意头、尾节点的插入方式与中间节点的不同
newNode = ListNode(value)
cnt = 2 # 从第二个节点开始,因为首节点已经先做过判断
if index == 1:
newNode.next = head
head = newNode # 统一返回 head 指针
pre, cur = head, head.next
while cur:
if cnt == index:
newNode.next = cur
pre.next = newNode
break
else:
cnt += 1
pre, cur = cur, cur.next
if cnt <= index: # 如果大于链表中节点数目,则直接加到链表尾部
pre.next = newNode
return head
def PrintList(self, head): # 打印链表
while head:
print(head.val, end=' ')
head = head.next
if __name__ == '__main__':
nums = [2, 7, 1, 4, 5]
a = Solution()
head = a.CreateList(nums)
# head = a.InsertNode(head, 6, 3)
# head = a.DeleteNode(head, 2)
a.PrintList(head)
python 实现单链表
最新推荐文章于 2024-02-21 11:26:23 发布