码迷,mamicode.com
首页 > 其他好文 > 详细

反转链表---简单

时间:2019-01-27 18:52:50      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:reserve   https   就是   nullptr   轻松   node   return   targe   ==   

题目:

  反转一个单链表。

示例:

输入: 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;      //每次递归都返回最后一个节点
        }
    }
};

 

反转链表---简单

标签:reserve   https   就是   nullptr   轻松   node   return   targe   ==   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!