Leetcode206||剑指offer16:反转链表

三种常用方法:顺次修改、头插法、递归法

顺次修改:

ListNode* reverseList(ListNode* head)
{
	if(head == nullptr || head->next == nullptr)
        return head;
    ListNode *pPrev = nullptr, *pCur = head, *pNext = nullptr;
    while(pCur)
    {
        pNext = pCur->next;
        pCur->next = pPrev;
        pPrev = pCur;
        pCur = pNext;
    }
    return pPrev;
}

头插法:借助头节点

ListNode* reverseList2(ListNode* head)
{
	if (head == nullptr || head->next == nullptr)
		return head;
	ListNode* dummy = new ListNode(0);
	ListNode* ptr = head;
	while (head)
	{
		head = head->next;
		ptr->next = dummy->next;
		dummy->next = ptr;
		ptr = head;
	}
	return dummy->next;
}

 

你可能感兴趣的:(Leetcode数据结构,剑指offer)