链表的逆置常作为应届生面试题,主要考察求职者对链表的理解,还有思维能力。逆置的思路主要是保存几个临时的指针变量,其实好多面试题都可以通过保存临时变量的方式来解决。
C++代码如下:
#include "stdafx.h"
struct ListNode
{
int m_nData;
ListNode* m_pNext;
};
ListNode* ReverseList(ListNode *pHead)
{
ListNode* pReversedHead = NULL;
ListNode* pNode = pHead;
ListNode* pPrev = NULL;
while(NULL != pNode)
{
ListNode* pNext = pNode->m_pNext;
if (NULL == pNext)
pReversedHead = pNode;
pNode->m_pNext = pPrev;
pPrev = pNode;
pNode = pNext;
}
return pReversedHead;
}
int _tmain(int argc, _TCHAR* argv[])
{
int len = 10;
ListNode *pHead = new ListNode;
pHead->m_nData = 10;
pHead->m_pNext = NULL;
ListNode *pPrev = pHead;
for (int i=0; i<len; i++)
{
ListNode *p = new ListNode;
p->m_nData = i;
p->m_pNext = NULL;
if (NULL != pPrev)
{
pPrev->m_pNext = p;
}
pPrev = p;
}
ListNode *pReversedHead = ReverseList(pHead);