• 【手撕】翻转链表


    #include<iostream>
    
    using namespace std;
    
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(nullptr) { }
    };
    
    class Solution
    {
    public:
        ListNode* reverseList(ListNode* head)
        {
            if (head == nullptr || head->next == nullptr)
            {
                return head;
            }
            ListNode* cur = head;
            ListNode* pre = nullptr;
            while (cur != nullptr)
            {
                ListNode* next = cur->next;
                cur->next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    };
    
    int main()
    {
        ListNode* node1 = new ListNode(1);
        ListNode* node2 = new ListNode(2);
        ListNode* node3 = new ListNode(3);
        ListNode* node4 = new ListNode(4);
        node1->next = node2;
        node2->next = node3;
        node3->next = node4;
        ListNode* head = node1;
        ListNode* cur = node1;
    
        cout << "翻转之前的链表为:";
        while (cur != nullptr)
        {
            cout << cur->val <<"->";
            cur = cur->next;
        }
        cout << "nullptr" << endl;
    
        Solution solution;
        cur = solution.reverseList(head);
    
        cout << "翻转之后的链表为:";
        while (cur != nullptr)
        {
            cout << cur->val << "->";
            cur = cur->next;
        }
        cout << "nullptr" << endl;
    
        return 0;
    }
  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/masbay/p/14194821.html
Copyright © 2020-2023  润新知