题目链接在此
Reverse a singly linked list.
反转一个单链表。别小看这道题啊,我TX面试上来就问这道题。当时我觉得用两个指针就够了——显然天真了,得用三个指针。
这是一个循环的算法:
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;
ListNode *q = head->next;
ListNode *r = head->next->next;
head->next = NULL;
while (true) {
q->next = p;
p = q;
q = r;
if (r != NULL)
r = r->next;
else
break;
};
return p;
}
};
以下则是递归做法:
class Solution2 {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* p = head;
while (p->next != NULL)
p = p->next;
reverse(head);
return p;
}
private:
ListNode* reverse(ListNode* head) {
if (head->next == NULL)
return head;
else {
ListNode* tail = reverse(head->next);
tail->next = head;
tail = tail->next;
tail->next = NULL;
return tail;
}
}
};