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;
            }
        }
    };

  • 相关阅读:
    前端性能优化
    技术从业者的未来(二)
    微服务架构
    SpringCloud 微服务最佳开发实践
    架构师之路
    SpringBoot开发秘籍
    架构设计方法论
    消息架构的设计难题以及应对之道
    SpringCloud 中如何防止绕过网关请求后端服务?
    微服务架构授权是在网关做还是在微服务做?
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4482958.html
Copyright © 2011-2022 走看看