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

    题目描述:

    解法一(迭代):

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

    解法二(递归):

    /**
     * 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* res=reverseList(head->next);
            head->next->next=head;
            head->next=NULL;
            return res;
        }
    };
  • 相关阅读:
    软件工程—附加作业
    软件工程最终总结
    电梯调度(两人结对)
    VS单元测试
    第二周作业(2,3题)
    VS的安装
    补救
    漂亮男孩不说谎
    博客带我成长
    Java后缀数组-求sa数组
  • 原文地址:https://www.cnblogs.com/oneDongHua/p/14264012.html
Copyright © 2011-2022 走看看