反转链表---简单

题目:

  反转一个单链表。

示例:

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

猜你喜欢

转载自www.cnblogs.com/manch1n/p/10327128.html
今日推荐