题目
Reverse a singly linked list.
反转链表
代码
递归实现
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* p = head->next;
head->next = NULL;
ListNode* newHead = reverseList(p);
p->next = head;
return newHead;
}
};
迭代实现
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* p = head;
ListNode* q = p->next;
p->next = NULL;
while (q != NULL) {
ListNode* t = q->next;
q->next = p;
p = q;
q = t;
}
return p;
}
};