题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。结点定义如下:
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
};
方法一:利用三个指针
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReverseHead = NULL;
ListNode* pNode = pHead;
ListNode* pre = NULL;
ListNode* pNext = NULL;
while (pNode != NULL)
{
pNext = pNode->next;
if (NULL == pNext)//下一个结点为空,逆置的头结点为当前结点
pReverseHead = pNode;
pNode->next = pre;//反转链表指向
pre = pNode;
pNode = pNext;
}
return pReverseHead;
}
};
方法二:头插法
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pCur = pHead;
ListNode* pNewHead = NULL;
ListNode* pNext = NULL;
while (pCur)
{
pNext = pCur->next;//保存下一结点的值
pCur->next = pNewHead;//头插进去
pNewHead = pCur;//新链表的头部更新
pCur = pNext;//当前结点走向下一个结点
}
return pNewHead;
}
};