首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >反转链表-递归的思想

反转链表-递归的思想

作者头像
seth-shi
发布2023-12-18 14:35:19
发布2023-12-18 14:35:19
3340
举报
文章被收录于专栏:seth-shi的专栏seth-shi的专栏

最近在LeetCode做题目,遇到一个反转链表的题目.

代码语言:javascript
复制
反转一个单链表。

示例:

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

迭代

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {

    struct ListNode *tmpHead = head, *nextNode;

    if (NULL == head) {

        return head;
    }

    while (NULL != head->next) {

        // 把当前 '头结点' 的下一个移动到 `真正的头结点`
        nextNode = head->next;
        head->next = head->next->next;

        nextNode->next = tmpHead;
        tmpHead = nextNode;
    }


    return tmpHead;
}

递归

代码语言:javascript
复制
//    反转一个单链表。(递归的方法)
//
//    示例:
//
//    输入: 1->2->3->4->5->NULL
//    输出: 5->4->3->2->1->NULL

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {

    if (NULL == head) {

        return NULL;
    }
    else if (NULL == head->next) {

        return head;
    }

    struct ListNode *currNode = reverseList(head->next);


    head->next->next = head;
    head->next = NULL;

    return currNode;
}


//    reverseList([1, 2, 3, 4, 5]) {
//
//        reverseList([2, 3, 4, 5]) {
//
//            reverseList([3, 4, 5]) {
//
//                reverseList([4, 5]) {
//
//                    reverseList([5]) {
//
//                        // 1. 这里 next 为 NULL, 所以返回当前自己
//                        return 5;
//                    }
//
//                    // 2. 这一步我们需要拿到 5 的指针指向 4
//                    // 并把 4 的 next 置空
//                    [4, 5]->next->next = [4, 5];
//                    [4, 5]->next = NULL;
//
//                    return [5, 4];
//                }
//
//                // 3. 这里的参数里实际上 5 已经被内层递归置为 NULL
//                // 这一步我们需要拿到 4 的指针,然后把它指向 3
//                // 并把 3 的 next 置空
//                [3, 4, '5']->next->next = [3, 5];
//                [3, 4]->next;
//
//                return [5, 4, 3];
//            }
//
//            // 4.
//            [2, 3, '4', '5']->next->next = [2, 3, '4', '5'];
//            [2, 3]->next = NULL;
//
//            return [5, 4, 3, 2];
//        }
//
//        // 5.
//        [1, 2, '3', '4', '5']->next->next = [1, 2, '3', '4', '5'];
//        [1, 2]->next = NULL;
//
//        return [5, 4, 3, 2, 1];
//    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-02-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 迭代
  • 递归
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档