标签:while 指针 ever 反转链表 new 注意 临时 忘记 odi
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        
标签:while 指针 ever 反转链表 new 注意 临时 忘记 odi
原文地址:https://www.cnblogs.com/wanrongshu/p/12737754.html