zoukankan      html  css  js  c++  java
  • 206.Reverse Linked List

    • 迭代:
    /**
     * 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* cur = head;
            ListNode* prev = NULL;
            while(cur != NULL){
                ListNode* next = cur->next;
                cur->next = prev;
                prev = cur;
                cur = next;
            }
            return prev;
        }
    
        
    };
    
    • 递归
    /**
     * 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;
            return getreverse(NULL,head);
        }
        
        ListNode* getreverse(ListNode* prev,ListNode* cur){        //每一次递归就相当于将cur和prev向前移动
            if(cur == NULL){
                return prev;
            }
            ListNode* next = cur->next;
            cur->next = prev;
            return getreverse(cur,next);
        }
        
    };
    
  • 相关阅读:
    [BZOJ2969] 矩形粉刷
    数字 (number)
    字符串(String)
    小HY的四元组
    最大公约数(Max Gcd)
    [洛谷P2102] 地砖铺设
    Python OS模块(内置模块)
    json解析神器--jsonpath
    kafka 优势+应用场景
    Python之异常处理
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7160073.html
Copyright © 2011-2022 走看看