- Reverse Linked List
方法一、采用非递归的方法,头插入法
ListNode* reverseList(ListNode* head) {
if(NULL == head || NULL == head->next)
{
return head;
}
ListNode* p1 = head; //存储逆转的链表的表头
ListNode* p2 = p1->next;
p1->next = NULL;
ListNode* tmp; //存储链表未逆转的链表的表头
while(p2)
{
tmp = p2->next;
p2->next = p1;
p1 = p2;
p2 = tmp;
}
return p1;
}
方法二、采用递归的方法
ListNode* reverseList(ListNode* head) {
if(NULL == head || NULL == head->next)
{
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}