• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

向小园

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

剑指offer 链表(下)

目录
  • T22-链表中倒数第k个节点
  • T24-反转链表
    • 非递归写法 py2
    • 递归写法 py2
  • [T35-复杂链表的复制]
  • [删除链表中重复的节点]

T22-链表中倒数第k个节点

注意走(k-1)步的循环中,判断p==None就返回,即链表长度小于k的情况

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if k<1 or not head:
            return None
        p,p1 = head,head
        for i in range(k-1):
            p = p.next
            if not p:
                return None
        while p.next:
            p = p.next
            p1 = p1.next
        return p1

T24-反转链表

非递归写法 py2

对于看似复杂的问题,看分解的每一部分怎么操作也许是最好的方法。 此题也是,只关注链表的每个节点,这个单向链表的节点,它的后节点指向变为哪里,而不关心多个节点是怎样连接的。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        ppre,pnext=None,None
        p = pHead
        while p:
            pnext = p.next
            p.next = ppre
            ppre = p
            p = pnext
        return ppre

递归写法 py2

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        return self._reverse(pHead,None)
    def _reverse(self,node,prev=None):
        if not node:
            return prev
        n = node.next
        node.next = prev
        return self._reverse(n,node)

[T35-复杂链表的复制]

[删除链表中重复的节点]

posted on 2020-03-03 17:35  向小园  阅读(127)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3