该题不同于第6题,第6题不可以链表的结构。而本题是要改变链表的节点指向顺序,所以改变了链表的结构。再原链表中我们用到了一根pNext指针指向下一个节点。同理,我们只要将链表所有的指针全都倒转过来就可实现本题要求。那么需要几根指针?
首先,我们需要一个指针记录当前节点位置,再来一根指针记录它的前一个节点,同时我们还需要在调整之前记录一下当前节点位置,否则当前节点把pNext指针断开后指向它前一个节点做反转工作,当前节点的下一个节点就找不到现在这个节点了。所以需要三根指针。
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int nValue;
struct list *pNext;
}List;
List *CreateList()
{
List *pHead = NULL;
List *pTail = NULL;
List *pTemp = NULL;
int nNum;
scanf("%d",&nNum);
while(nNum != 0)
{
pTemp = (List *)malloc(sizeof(List));
pTemp->nValue = nNum;
pTemp->pNext = NULL;
if(pHead == NULL)
{
pHead = pTemp;
}
else
{
pTail->pNext = pTemp;
}
pTail = pTemp;
scanf("%d",&nNum);
}
return pHead;
}
List *ReverseList(List *pHead) //本题关键代码
{
if(pHead == NULL || pHead->pNext == NULL) return pHead;
List *p1 = NULL;
List *p2 = pHead;
List *p3 = pHead->pNext;
while(p3 != NULL)
{
p2->pNext = p1;
p1 = p2;
p2 = p3;
p3 = p3->pNext;
}
p2->pNext = p1;
return p2;
}
void Print(List *pHead)
{
if(pHead == NULL) return;
while(pHead)
{
printf("%d ",pHead->nValue);
pHead = pHead->pNext;
}
}
int main()
{
List *pList = NULL;
pList = CreateList();
pList = ReverseList(pList);
Print(pList);
return 0;
}