Reverse Linked List Leetcode
阿新 • • 發佈:2017-06-05
|| val def reverse pub class light == ext
真的是太久太久沒有刷題了。。。。那天阿裏面到這麽簡單的題目發現自己都寫不利索了。。。哭瞎。。。
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