zoukankan      html  css  js  c++  java
  • leetcode 206 反转链表 Reverse Linked List

    C++解法一:迭代法,使用前驱指针pre,当前指针cur,临时后继指针nxt;

    /**
     * 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) {
            ListNode* pre=NULL,*cur=head;
            while(cur!=NULL){
                ListNode* nxt=cur->next;
                cur->next=pre;
                pre=cur;cur=nxt;
            }
            return pre;
        }
    };

    C++方法二:递归法,Space:O(n),Time O(n)

    /**
     * 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==NULL||head->next==NULL) return head;
            ListNode *p=reverseList(head->next);
            head->next->next=head;
            head->next=NULL;
            return p;
        }
    };
  • 相关阅读:
    optparse--强大的命令行参数处理包
    B/S和C/S架构的区别
    Document
    Document
    Document
    Document
    Document
    Document
    Document
    Document
  • 原文地址:https://www.cnblogs.com/joelwang/p/10447288.html
Copyright © 2011-2022 走看看