C代码: 单链表逆置
/*
Author : glq2000[glq2000@126.com http://hi.baidu.com/bmrs]
Date : Wen, 2010-7-21
功能 : 实现单链表的逆置等
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Node
{
int value;
struct _Node *next;
}Node, *PNode;
PNode BuildLink(int n); //构造一个节点数目为n个的链表, 返回链表头指针
PNode ReverseLink(PNode ph); //单链表的逆置函数,返回新链表的表头指针
void OutputLink(PNode ph); //输出单链表
int main()
{
PNode phead = BuildLink(10);
OutputLink(phead);
phead = ReverseLink(phead);
OutputLink(phead);
getchar();
return 0;
}
PNode BuildLink(int n)
{
int i;
PNode ph=NULL, pn;
for(i=0; i<n; ++i)
{
if(!(pn=(PNode)malloc(sizeof(Node))))
{
printf("malloc error.\n");
exit(1);
}
pn->value = i;
pn->next = ph;
ph = pn;
}
return ph;
}
void OutputLink(PNode ph)
{
while(ph)
{
printf("%d ", ph->value);
ph = ph->next;
}
printf("\n");
}
//实现单链表逆置的函数
PNode ReverseLink(PNode ph)
{
if(!ph || !(ph->next)) //如果链表为空或者只有一个节点,则直接返回
return ph;
PNode pBefore = NULL, pAfter = NULL;
while(ph)
{
pAfter = ph->next;
ph->next = pBefore;
pBefore = ph;
ph = pAfter;
}
return pBefore;
}
Author : glq2000[glq2000@126.com http://hi.baidu.com/bmrs]
Date : Wen, 2010-7-21
功能 : 实现单链表的逆置等
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Node
{
int value;
struct _Node *next;
}Node, *PNode;
PNode BuildLink(int n); //构造一个节点数目为n个的链表, 返回链表头指针
PNode ReverseLink(PNode ph); //单链表的逆置函数,返回新链表的表头指针
void OutputLink(PNode ph); //输出单链表
int main()
{
PNode phead = BuildLink(10);
OutputLink(phead);
phead = ReverseLink(phead);
OutputLink(phead);
getchar();
return 0;
}
PNode BuildLink(int n)
{
int i;
PNode ph=NULL, pn;
for(i=0; i<n; ++i)
{
if(!(pn=(PNode)malloc(sizeof(Node))))
{
printf("malloc error.\n");
exit(1);
}
pn->value = i;
pn->next = ph;
ph = pn;
}
return ph;
}
void OutputLink(PNode ph)
{
while(ph)
{
printf("%d ", ph->value);
ph = ph->next;
}
printf("\n");
}
//实现单链表逆置的函数
PNode ReverseLink(PNode ph)
{
if(!ph || !(ph->next)) //如果链表为空或者只有一个节点,则直接返回
return ph;
PNode pBefore = NULL, pAfter = NULL;
while(ph)
{
pAfter = ph->next;
ph->next = pBefore;
pBefore = ph;
ph = pAfter;
}
return pBefore;
}