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

    题目:

    Reverse a singly linked list.

    提示:

    此题不难,可以用迭代或者递归两种方法求解。记得要把原来的链表头的next置为NULL;

    代码:

    迭代:

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

    递归:

    /**
     * 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) {
            return reverseNode(head, NULL);
        }
        
        ListNode* reverseNode(ListNode* head, ListNode* newHead) {
            if (!head) return newHead;
            ListNode *next = head->next;
            head->next = newHead;
            return reverseNode(next, head);
        }
    };
  • 相关阅读:
    Odoo权限设置机制
    Odoo10配置文件
    Odoo10——self的使用
    Odoo10 启动选项
    ubuntu安装nginx
    pycharm快捷键一览
    前端 -- HTML
    前端 -- CSS
    前端 -- JavaScript
    前端 -- BOM和DOM
  • 原文地址:https://www.cnblogs.com/jdneo/p/4798392.html
Copyright © 2011-2022 走看看