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

    Reverse Linked List

    Reverse a singly linked list.

    click to show more hints.

    Hint:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    解法一:非递归

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

    解法二:递归

    每个节点都调到尾部去

    /**
     * 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* newhead = head;
            while(newhead->next != NULL)
                newhead = newhead->next;
            reverse(head);
            return newhead;
        }
        ListNode* reverse(ListNode* head)
        {
            if(head->next == NULL)
                return head;
            else
            {
                ListNode* tail = reverse(head->next);
                tail->next = head;
                tail = tail->next;
                tail->next = NULL;
                return tail;
            }
        }
    };

  • 相关阅读:
    Maven项目类型和JAVASE项目和JAVAEE项目的关系
    使用faker 生成测试数据
    python 面向对象
    python csv读写
    分治
    django 部署
    js 时间格式转换
    python环境
    枚举
    递归
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4482958.html
Copyright © 2011-2022 走看看