206. Reverse Linked List
Description
Reverse a singly linked list.
Solution
- 题意即将一个链表倒转。
- 有两种方式,迭代和递归,代码如下。
// 迭代
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre = NULL;
while (head) {
ListNode *p = head->next;
head->next = pre;
pre = head;
head = p;
}
return pre;
}
};
// 递归
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;
}
};