24.反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
双指针
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p1 = NULL;
ListNode* pre = head;
ListNode* cur = head;
while(cur != NULL)
{
cur = cur->next;
pre->next = p1;
p1 = pre;
pre =cur;
}
return p1;
}
};
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* ret;
ret = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return ret;
}
};
就地逆置双指针
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return head;
ListNode* cur = head;
ListNode* pre = head;
while(head->next!=NULL)
{
cur = head->next;
head->next= cur->next;
cur->next=pre;
pre=cur;
}
return pre;
}
};