剑指OFFER-反转链表

剑指OFFER-反转链表

Question

输入一个链表,反转链表后,输出新链表的表头。
关键词:链表 反转

Solution

遍历反转

时间复杂度:O(N)
空间复杂度:O(1)

  • Python
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead:
            return pHead
        else:
            head = pHead
            tail = head.next
            head.next = None
        while tail:
            tail.next, tail, head = head, tail.next, tail
        return head
  • C++
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (!pHead || !pHead->next)
            return pHead;
        
        ListNode* head = pHead;
        ListNode* tail = pHead->next;
        head->next = NULL;
        while(tail){
            ListNode* temp1 = tail->next;
            tail->next = head;
            ListNode* temp2 = tail;
            tail = temp1;
            head = temp2;
        }
        return head;
    }
};

递归

时间复杂度:O(N)
空间复杂度:O(…)

  • Python
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
    	## 终止条件
    	if not pHead or not pHead.next:
            return pHead
        ## 递归
        re_head = self.ReverseList(pHead.next)
        pHead.next.next = pHead
        pHead.next = None
        ## 每轮返回值为已反转的链表表头,即永远是原链表的表尾
        return re_head
  • C++
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
    	// 终止条件
        if (!pHead || !pHead->next)
            return pHead;
        // 递归
        ListNode* re_head = ReverseList(pHead->next);
        // 每轮递归的额外操作
        pHead->next->next = pHead;
        pHead->next = NULL;
        
        return re_head;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值