Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目描述:反转链表
解法一:递归
/**
* 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 *nHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return nHead;
}
};
解法二:非递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return NULL;
ListNode *nHead = NULL;
ListNode *ptr = head;
while(head){
ptr = head;
head = head->next;
ptr->next = nHead;
nHead = ptr;
}
return nHead;
}
};