五分钟搞定一道算法题:Reverse Linked List

《五分钟搞定一道算法题:Reverse Linked List》 image

LeetCode上第206号问题:Reverse Linked List

题目

反转一个单链表。

示例:

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

进阶:

你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

解题思路

设置三个节点precurnext

  • (1)每次查看cur节点是否为NULL,如果是,则结束循环,获得结果
  • (2)如果cur节点不是为NULL,则先设置临时变量nextcur的下一个节点
  • (3)让cur的下一个节点变成指向pre,而后pre移动curcur移动到next
  • (4)重复(1)(2)(3)

动画演示

动画演示GIF有点大,请稍微等待一下加载显示_

《五分钟搞定一道算法题:Reverse Linked List》 动画演示

参考代码

迭代的方式处理
// 206. Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/description/
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
public:
    ListNode* reverseList(ListNode* head) {

        ListNode* pre = NULL;
        ListNode* cur = head;
        while(cur != NULL){
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }
};

递归的方式处理
// 206. Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/description/
//
// 递归的方式反转链表
// 时间复杂度: O(n)
// 空间复杂度: O(1)
class Solution {
public:
    ListNode* reverseList(ListNode* head) {

        // 递归终止条件
        if(head == NULL || head->next == NULL)
            return head;

        ListNode* rhead = reverseList(head->next);

        // head->next此刻指向head后面的链表的尾节点
        // head->next->next = head把head节点放在了尾部
        head->next->next = head;
        head->next = NULL;

        return rhead;
    }
};

执行结果

《五分钟搞定一道算法题:Reverse Linked List》 image
《五分钟搞定一道算法题:Reverse Linked List》 QQ20181217-142752.png

    原文作者:程序员小吴师兄
    原文地址: https://www.jianshu.com/p/3af83e7049c6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞