首页 > 其他 > 详细

反转链表---简单

时间:2019-01-27 18:35:31      阅读:132      评论:0      收藏:0      [点我收藏+]

题目:

  反转一个单链表。

示例:

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

思路:

  这道题比较经典,可以用递归与循环做。先说循环的:双指针加一个保留指针,轻松搞定。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr)
        {
            return head;
        }
        auto p=head,q=head->next;
        p->next=nullptr;
        ListNode* reserve=q->next;
        while(1)
        {
            q->next=p;
            p=q;
            q=reserve;
            if(reserve==nullptr)
            {
                return p;
            }
            reserve=reserve->next;
        }
    }
};

  递归的有点难想呢。https://www.cnblogs.com/kubixuesheng/p/4394509.html

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr||head->next==nullptr)
        {
            return head;
        }                      //找到最后一个节点
        else
        {
            auto p=reverseList(head->next);    //p就是最后一个节点
            head->next->next=head;       
            head->next=nullptr;
            return p;      //每次递归都返回最后一个节点
        }
    }
};

 

反转链表---简单

原文:https://www.cnblogs.com/manch1n/p/10327128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!