首页 > 代码库 > Reverse Linked List Leetcode

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