zoukankan      html  css  js  c++  java
  • 链表倒置,这个还是考验仔细程度,第一遍还没做对 —— 剑指Offer

    https://www.nowcoder.net/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述

    输入一个链表,反转链表后,输出链表的所有元素。

    思路:

    还是要用三个指针,但是要考虑退出条件。完全的没有前后特殊情况的处理,看起来不行。为了保持优雅性,我把特殊处理放在了最前面。

    但是最开始有一个bug,就是初始的时候有两句前后顺序颠倒了。倒置不能正常工作,后来可以了。

    代码:

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* ReverseList(ListNode* pHead) {
            if (pHead == NULL || pHead->next == NULL) return pHead;
            
            ListNode *pFirst = NULL;
            ListNode *pSecond = pHead;
    // 开始下面两行倒了,有bug ListNode
    *pThird = pSecond->next; pSecond->next = pFirst; while (pThird != NULL) { pFirst = pSecond; pSecond = pThird; pThird = pThird->next; pSecond->next = pFirst; } return pSecond; } };

  • 相关阅读:
    寒假周总结一
    1657. Determine if Two Strings Are Close
    1656. Design an Ordered Stream
    695. Max Area of Island (BFS)
    695. Max Area of Island (DFS)
    Daily Coding Problem: Problem #713
    939. Minimum Area Rectangle
    259. 3Sum Smaller
    29. Divide Two Integers
    16. 3Sum Closest
  • 原文地址:https://www.cnblogs.com/charlesblc/p/8434819.html
Copyright © 2011-2022 走看看