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

    时间限制:1秒 空间限制:32768K 热度指数:281981
    本题知识点: 链表

     算法知识视频讲解

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。
    给出代码:
    /*
    struct ListNode {
    	int val;
    	struct ListNode *next;
    	ListNode(int x) :
    			val(x), next(NULL) {
    	}
    };*/
    class Solution {
    public:
        ListNode* ReverseList(ListNode* pHead) {
    
        }
    };
    

      

    我写的代码太丑了,直接贴一段牛客讨论里的代码 ,写的很清晰

    AC代码:

    链接:https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
    来源:牛客网
    
    //第一种方法是:非递归方法
    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* ReverseList(ListNode* pHead) {
             
            if(pHead==NULL) return NULL;//注意程序鲁棒性
             
            ListNode* pNode=pHead;//当前指针
            ListNode* pReverseHead=NULL;//新链表的头指针
            ListNode* pPrev=NULL;//当前指针的前一个结点
             
            while(pNode!=NULL){//当前结点不为空时才执行
                ListNode* pNext=pNode->next;//链断开之前一定要保存断开位置后边的结点
                 
                if(pNext==NULL)//当pNext为空时,说明当前结点为尾节点
                    pReverseHead=pNode;
      
                pNode->next=pPrev;//指针反转
                pPrev=pNode;
                pNode=pNext;
            }
            return pReverseHead;
        }
    }
     
    //第二种方法是:递归方法 /*
    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* pReverseNode=ReverseList(pHead->next);
             
            //再将当前节点设置为后面节点的后续节点
            pHead->next->next=pHead;
            pHead->next=NULL;
             
            return pReverseNode;
             
        }
    };
    

      

  • 相关阅读:
    Python安装
    Python的种类
    Windows server 下 DNS服务器 实现递归查询和循环查询的配置方法
    Command Injection_low、Medium、high、Impossible
    Brute Force_impossible
    Brute Force_high
    Brute Force_medium
    Brute Force_low
    脚本黑客1----HTML基础笔记
    windows服务器大量端口被dns.exe占用的解决方法
  • 原文地址:https://www.cnblogs.com/Hyouka/p/9268574.html
Copyright © 2011-2022 走看看