描述:反转单链表的值,但不改变链表指针地址,一个单链表比如1->2->3->4,在不改变指针地址的情况下把链表变为4->3->2->1.
代码:
#include<stdio.h>
#include<stdlib.h>
typedefstruct Node
{
int value;
struct Node *next;
}*pNode;
void ReverseValue(pNode &pStart,pNode pNext)
{
if(pNext==NULL||pStart==pNext||pStart->next==pNext)
return;
ReverseValue(pStart,pNext->next);
int temp=pStart->value;
pStart->value=pNext->value;
pNext->value=temp;
pStart=pStart->next;
}
void Reverse(pNode pStart)
{
if(pStart==NULL)
return;
ReverseValue(pStart,pStart);
}
pNode CreateNodeList(int n)
{
if(n<=0)
return NULL;
else
{
pNode pStart=NULL,Temp=NULL;
int value=0;
for(int i=0;i<n;i++)
{
printf("Value:");
scanf("%d",&value);
Temp=(pNode)malloc(sizeof(struct Node));
Temp->value=value;
if(i==0)
{
Temp->next=NULL;
pStart=Temp;
}
else
{
Temp->next=pStart;
pStart=Temp;
}
}
return pStart;
}
}
void PrintNode(pNode node)
{
while(node!=NULL)
{
printf("Node Value:%d\n",node->value);
node=node->next;
}
printf("\n");
}
void main()
{
pNode node=CreateNodeList(4);
PrintNode(node);
Reverse(node);
PrintNode(node);
}
运行结果:
Value:1
Value:2
Value:3
Value:4
Node Value:4
Node Value:3
Node Value:2
Node Value:1
Node Value:4
Node Value:3
Node Value:2
Node Value:1