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

    Reverse a singly linked list.

    思路:递归,每次保存一下上一个节点用来构造反转后的链表。
    非递归,需要多记录两个值.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* ans = nullptr;
        void dfs(ListNode* p, ListNode* q) {
            if (p == nullptr) {
                ans = q;
                return ;
            }
            dfs(p->next, p);
            p->next = q;
            if (q) q->next = nullptr;
        } 
        ListNode* reverseList(ListNode* head) {
            dfs(head, nullptr);
            return ans;
        }
    };
    
    
    /**
     * 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 *prev = NULL;
            ListNode *next = NULL;
    
            while (head) {
                next = head->next;
                head->next = prev;
                prev = head;
                head = next;
            }
            return prev;
        }
    };
    
  • 相关阅读:
    mysql分表分库 ,读写分离
    二级域名解析设置及Apache 子域名配置
    PHP错误检测
    PHP缓存技术相关
    高并发一些处理办法
    memcached 安装与简单实用使用
    数据库入门
    函数
    结构体 枚举
    c# 6大类集合
  • 原文地址:https://www.cnblogs.com/pk28/p/8485033.html
Copyright © 2011-2022 走看看