zoukankan      html  css  js  c++  java
  • 剑指offer-面试题24-反转链表-链表

    /*
    题目:
    	定义一个函数,输入链表的头结点,反转链表输出反转后链表的头节点。
    */
    /*
    思路:
    	记录当前节点的next和pre。
    	断开当前节点指向next的指针,指向pre。
    */
    #include <iostream>
    #include<cstdlib>
    
    using namespace std;
    
    struct ListNode {
    	int val;
    	struct ListNode *next;
    	ListNode(int x) :
    			val(x), next(NULL) {
    	}
    };
    
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == nullptr || pHead->next == nullptr) return pHead;
    
        ListNode* pre = pHead;
        ListNode* curr = pHead->next;
        pre->next = nullptr;
        ListNode* next = nullptr;
        while(curr){
            next = curr->next;
            curr->next =pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
    
    int main()
    {
        ListNode *node6 = new ListNode(6);
        ListNode *node5 = new ListNode(5);
        ListNode *node4 = new ListNode(4);
        ListNode *node3 = new ListNode(3);
        ListNode *node2 = new ListNode(2);
        ListNode *node1 = new ListNode(1);
        ListNode *pHead = new ListNode(0);
        pHead->next = node1;
        node1->next = node2;
        node2->next = node3;
        node3->next = node4;
        node4->next = node5;
        node5->next = node6;
        node6->next = nullptr;
    
        pHead = ReverseList(pHead);
        cout<<"answer"<<endl;
        while(pHead != nullptr){
            cout<<pHead->val<<endl;
            pHead = pHead->next;
        }
    
    
        cout << "Hello world!" << endl;
        return 0;
    }
    

        

  • 相关阅读:
    Aapache Tomcat AJP 文件包含漏洞(CVE-2020-1938)
    Tomcat 任意文件上传漏洞(CVE-2017-12615)
    Apache Shiro 1.2.4反序列化漏洞(CVE-2016-4437)
    Redis 4.x/5.x 未授权访问漏洞
    mysql 5.7关于group by显示多列的一个潜坑
    Python
    购物车作业
    Lesson2
    a good website to test OTP
    利用fidder发送request
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11904751.html
Copyright © 2011-2022 走看看