Reverse Linked List Leetcode

Posted 璨璨要好好学习

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reverse Linked List Leetcode相关的知识,希望对你有一定的参考价值。

真的是太久太久没有刷题了。。。。那天阿里面到这么简单的题目发现自己都写不利索了。。。哭瞎。。。

Reverse a singly linked list.

可以用递归和非递归的方法。

递归:

主要思想是定义一个nextNode,用nextNode作为尾部直接连前面一个。

public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode nextNode = head.next;
        ListNode newHead = reverseList(nextNode);
        nextNode.next = head;
        head.next = null;
        return newHead;
    }
}

非递归:

public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

C++做法,虽然现在还不懂这个ListNode*是什么意思。。。。

递归:

/**
 * 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* node = head->next;
        ListNode* newHead = reverseList(node);
        node -> next = head;
        head -> next = NULL;
        return newHead;
    }
};

 非递归:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head -> next == NULL) {
            return head;
        }
        ListNode* pre = NULL;
        while (head != NULL) {
            ListNode* next = head -> next;
            head -> next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
};

 

以上是关于Reverse Linked List Leetcode的主要内容,如果未能解决你的问题,请参考以下文章

206. Reverse Linked List

206. Reverse Linked List

链表-Reverse Linked List

206. Reverse Linked List

Reverse Linked List

[Algorithm] 234. Palindrome Linked List / Reverse linked list