LenleDaytoy

剑指offer-24.反转链表

 

反转链表(实现链表的逆序)

法一:就地逆序。使用三个指针pre,curnext表示前驱节点,当前节点和后继节点。主要通过将当前节点的下一个指向赋值为前驱节点完成逆序。(cur.next=pre)【或者说是在遍历的时候,将当前结点的尾结点和前一个结点的替换】时间复杂度为O(n),改变了链表结构。

法二:递归法。时间复杂度为O(n),需要递归调用,性能有所下降。

法三:  插入法。从链表第二个节点开始,把遍历到的节点插入到头结点的前面,遍历完所有节点即实现链表的逆序。时间O(n),不需要递归,效率较高

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        

  

posted on 2020-04-20 14:50  LenleDaytoy  阅读(87)  评论(0编辑  收藏  举报

导航