zoukankan      html  css  js  c++  java
  • 剑指offer:反转链表

    题目描述:

    输入一个链表,反转链表后,输出新链表的表头。

    解题思路:

    思路一:先遍历一次链表,将每个结点存入栈中,再清空栈,构造新的链表,当前结点的下一个结点都为从栈新取出的结点,同时结点后移,指向这个新取出的结点。例如,用tmp表示新链表,cur = s.top(); cur->next = nullptr; tmp->next = cur. 注意需要判断当前栈中结点数量,若取完栈顶元素后无栈为空,则不再更新tmp = tmp->next。

    思路二:看了一下网上有更简单清晰的思路,用三个指针来维护整个链表,cur指向当前结点,pre指向前一个结点,nex指向后一个结点。

    代码:

    思路一:

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* ReverseList(ListNode* pHead) {
            if(pHead==nullptr)
                return pHead;
            ListNode *new_pHead, *tmp, *cur;
            tmp = pHead;
            stack<ListNode*> s;
            while(tmp!=nullptr)
            {
                s.push(tmp);
                tmp = tmp->next;
            }
            tmp = s.top();
            s.pop();
            new_pHead = tmp;
            while(!s.empty())
            {
                cur = s.top();
                cur->next = nullptr;
                s.pop();
                tmp->next = cur;
                if(s.size()>0)
                    tmp = tmp->next;
            }
            return new_pHead;        
        }
    };

    思路二:

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* ReverseList(ListNode* pHead) {
            if(pHead==nullptr)
                return pHead;
            ListNode *cur, *pre, *nex, *new_pHead;
            pre = nullptr;
            cur = pHead;
            while(cur!=nullptr)
            {
                nex = cur->next;
                if(nex == nullptr)
                    new_pHead = cur;
                
                cur->next = pre;
                pre = cur;
                cur = nex;
            }
            return new_pHead;
        }
    };
  • 相关阅读:
    《剑指offer》第十二题(矩阵中的路径)
    《剑指offer》第十五题(二进制中1的个数)
    《剑指offer》第十题(斐波那契数列)
    《剑指offer》第十一题(旋转数组的最小数字)
    原始的生成对抗网络GAN
    《剑指offer》第九题(用两个栈实现队列)
    (转)c++一些知识点
    贪心算法
    动态规划——最长公共子串
    动态规划——主元素算法
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/10590609.html
Copyright © 2011-2022 走看看