反转单链表的值,但不改变链表指针地址

描述:反转单链表的值,但不改变链表指针地址,一个单链表比如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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值