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; } };

  • 相关阅读:
    python基础语法
    DNS解析原理
    (4)获取servlet常用api
    (2)struts2配置祥解
    (1)WEB框架概念和struts2体验
    10.1--登录认证拦截器
    10--拦截器
    9--RESTful支持
    8--json交互
    7---上传图片
  • 原文地址:https://www.cnblogs.com/charlesblc/p/8434819.html
Copyright © 2011-2022 走看看