python链表详细讲解_剑指offer详解(链表)——python

# -*- coding:utf-8 -*-

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

# 返回从尾部到头部的列表值序列,例如[1,2,3]

def printListFromTailToHead(self, listNode):

# write code here

if not listNode:

return []

l=[]

while listNode:

l.append(listNode.val)

listNode=listNode.next

return l[::-1]class Solution:

def FindKthToTail(self, head, k):

# write code here

if not head or k<=0: return None

p=q=head

t=0

while p and t < k: # 将两个指针隔开k的距离

p=p.next

t+=1

if t

while p!=None: # 否则将从头的链表移动到已经移动的链表移动到结尾为止

q=q.next

p=p.next

return q

同时也是206. 反转链表(leetcode)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

迭代解法:class Solution:

def reverseList(self, head: ListNode) -> ListNode:

cur, pre = head, None

while cur:

temp=cur.next # 保存原链表后续的内容,不让链表断掉。temp就是原链表从第二个节点开始的一个链表

cur.next=pre #把cur的指针直接指向pre

pre=cur # 替换这个改造后的pre

cur=temp # 替换这个改造后的cur

return pre# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

# 返回合并后列表

def Merge(self, pHead1, pHead2):

# write code here

if pHead1 == None:

return pHead2

if pHead2 == None:

return pHead1

cur = ListNode(0)

# while pHead1 and pHead2:

if pHead1.val<= pHead2.val:

cur=pHead1

cur.next=self.Merge(pHead1.next, pHead2)

else :

cur=pHead2

cur.next=self.Merge(pHead1, pHead2.next)

return cur

用递归去做,会很简单,但这题可能不适合pythonclass Solution:

# 返回 RandomListNode

def Clone(self, pHead):

# write code here

if not pHead: return None

pCopy=RandomListNode(pHead.label) # 新建一个和pHead一样内容的RandomListNode对象

pCopy.random=pHead.random # 一个RandomListNode需要指定的值就是random和next

# pCopy.next=pHead.next

pCopy.next=self.Clone(pHead.next)

return pCopy

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值