链表 浅刷一下吧

单链表

在这里插入图片描述

创建链表

# 创建链表
class Node:
  # constructor
  def __init__(self, x, next=None): 
    self.val = x
    self.next = next

在这里插入图片描述

添加操作:先让先来的节点有所指向

在这里插入图片描述

#插入 第一步初始化
cur = ListNode(9)
#指向15 head的两个箭头 几个箭头就几个next
cur.next = head.next.next
head.next.next = cur

在这里插入图片描述

#在开头添加结点
cur = ListNode(9)
cur.next = head
head = cur
#结尾添加节点
cur = ListNode(9)
dum = head
while head.next:
    head = head.next
head.next = cur
head = dum

反转链表:双指针

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

def ReverseList(self , head: ListNode) -> ListNode:
        cur , pre = head, None
        while cur:
            temp = cur.next 
            cur.next = pre
            pre = cur
            cur = temp 
            
        return pre

合并两个排序的链表:继续双指针

在这里插入图片描述

#双指针
class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        # 初始化exp的head节点
        cur = dum = ListNode(0)
        while pHead1 and pHead2:#两个链表指针指向害不为空时
            if pHead1.val < pHead2.val:
                cur.next = pHead1 #expect接上1的
                pHead1 = pHead1.next #1链表指针前移
            else:
                cur.next = pHead2
                pHead2 = pHead2.next
            cur = cur.next #记得exp的指针异动
            #三元组写法 if A不为空输出 A 其他输出B
        cur.next = pHead1 if pHead1 else pHead2
        return dum.next

链表中倒数最后k个结点:顺序查找

class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        #算出链表长度n
        cur = pHead
        n = 0
        while cur:
            cur = cur.next 
            n +=1
        #输出位置为n-k的节点 要考虑k>n节点不存在
        cur = pHead
        if n - k < 0 :
            cur = None
        else:
            for i in range(n-k):
                cur = cur.next 
        return cur
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值