给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
标签:
['递归', '链表']难度:Easy
喜欢:2665class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while (cur){
ListNode* next = cur-> next;
cur-> next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL ) return head;
ListNode* tail = reverseList(head->next); // head->next的反转结果,返回链表头
head->next->next = head; // 头部两个元素进行反转
head->next = NULL;
return tail;
}
};