#include
#include
struct ListNode
{
int nKey;
ListNode * pNext;
};
void InitList(ListNode *, int);
void ReverseList(ListNode *, ListNode *);
void ShowList(ListNode *);
void main()
{
ListNode HeadList; //无效的头结点
ListNode RevHeadList; //无效的头结点
ListNode * pHead = NULL;
ListNode * pRevHead = NULL;
HeadList.nKey = -1;
HeadList.pNext = NULL;
RevHeadList.nKey = -1;
RevHeadList.pNext = NULL;
pHead = &HeadList;
pRevHead = &RevHeadList;
InitList(pHead, 10);
printf("原始链表数据:\n");
ShowList(pHead);
ReverseList(pHead, pRevHead);
printf("\n链表反正后的数据:\n");
ShowList(pRevHead);
return;
}
void InitList(ListNode * pHead, int n)
{
ListNode * pCurrent = NULL;
ListNode * pNext = NULL;
pCurrent = pHead;
for(int i = 0; i < n; i++)
{
pNext = (ListNode *)malloc( sizeof(ListNode) );
pNext->nKey = i;
pNext->pNext = NULL;
pCurrent->pNext = pNext;
pCurrent = pCurrent->pNext;
}
return;
}
void ReverseList(ListNode * pHead, ListNode * pRevHead)
{
ListNode * pCurrent = NULL;
ListNode * pNext = NULL;
if(pHead == NULL)
return;
pCurrent = pHead->pNext;
if( pCurrent == NULL)
return;
while(pCurrent)
{
pNext = pCurrent->pNext;
pCurrent->pNext = pRevHead->pNext;
pRevHead->pNext = pCurrent;
pCurrent = pNext;
}
return;
}
void ShowList(ListNode * pHead)
{
ListNode * pCurrent = NULL;
if(pHead == NULL)
return;
pCurrent = pHead->pNext;
if( pCurrent == NULL)
return;
while(pCurrent)
{
printf("%d\n",pCurrent->nKey);
pCurrent = pCurrent->pNext;
}
}