206. Reverse Linked List【easy】
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
解法一:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * pre = NULL; while (head != NULL) {
ListNode * next = head->next;
head->next = pre;
pre = head;
head = next;
} return pre;
}
};
解法二:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};
参考了@jianchao.li.fighter 的代码
The basic idea of this recursive solution is to reverse all the following nodes after head
. Then we need to set head
to be the final node in the reversed list. We simply set its next node in the original list (head -> next
) to point to it and sets its next
to be NULL
.
解法三:
public ListNode reverseList(ListNode head) {
/* recursive solution */
return reverseListInt(head, null);
} private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}
参考了@braydenCN 的代码