首页 > 其他 > 详细

剑指offer-24.反转链表

时间:2020-04-20 15:08:42      阅读:59      评论:0      收藏:0      [点我收藏+]
 

1.递归法

# -*- 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
        
        newhead=self.ReverseList(pHead.next)
        pHead.next.next=pHead
        pHead.next=None
        
        return newhead  

2.指针法:定义三个指针,分别指向当前遍历到的节点,它的前一个节点以及后一个节点。  

# -*- 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
        
        cur=pHead
        pre=None              #pre不要忘记写在最前面,因为第一个节点的next要置空
        while cur:
            next=cur.next   #注意这四行代码的对角线是相同的,按照这个规则写
            cur.next=pre    #比较简单,记住第一步是把当前节点的下一个节点保存好
            pre=cur          #next必须是一个临时(局部)变量,先要判断cur是为空, 
            cur=next       #防止链表断开
        return pre        

  

剑指offer-24.反转链表

原文:https://www.cnblogs.com/wanrongshu/p/12737754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!