Reverse a singly linked list.
单链表的逆序有两种方法,一种是递归的,另一种是非递归的(头插法)。
递归解法如下,耗时11ms:
/**
* 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* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
非递归解法如下,耗时8ms:
/**
* 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* p = head->next;
head->next = NULL;
ListNode* q;
while(p) {
q = p;
p = p->next;
q->next = head;
head = q;
}
return head;
}
};