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

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    code1:迭代

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(!head)
                return nullptr;
            else if(!head->next)
                return head;
            
            ListNode *newHead=head;
            ListNode *pre=nullptr;
            while(true)
            {
                ListNode *next=newHead->next;
                newHead->next=pre;
                pre=newHead;
                if(!next)
                    break;
                newHead=next;
            }
            return newHead;
        }
    };

     code2:递归

      翻转链表要保存前结点的信息,所以可先翻转head->next,即翻转后面的链表,待后面的链表反转完成后,让最新的尾结点指向的next指向head即可,所以递归参数要head->next

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(!head||!head->next)//当走到最后一个结点时,会返回,head不会为nullptr
                return head;
    
            ListNode *tmp=reverseList(head->next);//tmp指向最后一个结点,也就是最新的头结点,它会从最深层递归依次向上返回该值
            head->next->next=head;
            head->next=nullptr;
            return tmp;
        }
    };
  • 相关阅读:
    田忌赛马 题解
    亚历山大的丢番图方程 题解
    zhx's contest题解
    芝麻OI比赛T7edges题解
    CSP-J2020游记
    Linux shell 学习笔记(五)
    Linux shell 学习笔记(四)
    Linux shell 学习笔记(三)
    Linux shell 学习笔记(二)
    Oracle并发
  • 原文地址:https://www.cnblogs.com/tianzeng/p/11947219.html
Copyright © 2011-2022 走看看