码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List Leetcode

时间:2017-06-05 10:32:23      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:pre   list   div   非递归   tco   c++   efi   意思   ever   

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

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

标签:pre   list   div   非递归   tco   c++   efi   意思   ever   

原文地址:http://www.cnblogs.com/aprilyang/p/6943148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!