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;
}
};
本文介绍了单链表逆序的两种方法:递归和非递归。递归方法耗时11ms,非递归方法耗时8ms。通过代码实现展示了这两种方法的具体步骤。
534

被折叠的 条评论
为什么被折叠?



