初次编辑时间:2010-04-24
源程序及注释://SingleLinkRev.cpp
#include<stdio.h>
#include<stdlib.h>
#define ElemType int //链表数据域数据类型规定为整型
#define STATUS int
#define FAILURE 0
#define SUCCESS 1
typedef struct LNode
{ //定义链表结点及链表
ElemType data;
struct LNode *next;
}LNode,*LinkList;
STATUS InitLinkList(LinkList &L)
{ //初始化(新建)链表
if(!(L=(LNode *)malloc(sizeof(LNode)))) //内存申请失败
{
printf("OverFlow !\n");
return FAILURE;
}
else
{
L->next=NULL;
return SUCCESS;
}
}
STATUS AppendLinkList(LinkList &L)
{ //尾插法扩展链表结点
LNode *pN,*qN;
if(!L) //若链表为空新建链表
if(!(InitLinkList(L))) //建立链表失败
return FAILURE;
if(!(pN=(LNode *)malloc(sizeof(LNode)))) //内存申请失败
{
printf("OverFlow !\n");
return FAILURE;
}
scanf("%d",&(pN->data)); //处理新结点
pN->next=NULL;
qN=L;
while(qN->next) //若未到链表末尾
qN=qN->next;
qN->next=pN; //将结点加入链表末尾
return SUCCESS;
}
STATUS ReverseLinkList(LinkList &L)
{ //实现链表逆置
LNode *p,*q;
if(!L)
{
printf("LinkList don't exist!\n");
return FAILURE;
}
p=L->next;
if(p==NULL)
return SUCCESS;
q=p->next;
while(q)
{
p->next=q->next;
q->next=L->next;
L->next=q;
q=p->next;
}
return SUCCESS;
}
STATUS PrintLinkList(LinkList L)
{ //打印链表信息
if(!L) //若链表为空
{
printf("LinkList don't exist!\n");
return FAILURE;
}
L=L->next;
while(L)
{
printf("%d ",L->data);
L=L->next;
}
printf("\n");
return SUCCESS;
}
STATUS DestroyLinkList(LinkList &L)
{ //销毁链表
LNode *p;
while(L)
{
p=L->next;
free(L);
L=p;
}
return SUCCESS;
}
int main() //单链表就地逆置(多组测试数据 有注释).cpp
{
int i,n;
LinkList L;
printf("Input Any Integer n(n>0) Standing For The Number Of Node\nIn Your LinkList:");
scanf("%d",&n);
do{ //实现多组测试数据
if(!(InitLinkList(L)))
{
printf("Buiding LinkLsit Failure!\n");
exit(0);
}
for(i=1;i<=n;i++)
if(!AppendLinkList(L))
{
printf("Appending LNode Failure!\n");
exit(0);
}
printf("The original LinkList:\n");
PrintLinkList(L); //打印原始链表
if(!ReverseLinkList(L)) //实现链表逆置
{
printf("Reversing LinkList Failure!\n");
exit(0);
}
printf("The LinkList After Reversing:\n");
PrintLinkList(L); //打印逆置后链表
if(!DestroyLinkList(L)) //销毁链表
{
printf("Destroying LinkList Failure!\n");
exit(0);
}
printf("If You Want to Try Again,Input Any Integer n(n>0) Standing For\n");
printf("The Number Of Node In Your LinkList,Else Input 0:");
}while(scanf("%d",&n)!=EOF&&n!=0);
return 0;
}
说明:
1.主程序中包含了一个while语句以实现多组测试数据。该函数定义了几个函数以实现相应功能:
STATUS InitLinkList(LinkList &L) 初始化单链表;
STATUS AppendLinkList(LinkList &L) 尾插法扩展链表结点;
STATUS ReverseLinkList(LinkList &L) 实现链表逆置;
STATUS PrintLinkList(LinkList L) 打印链表信息;
STATUS DestroyLinkList(LinkList &L) 销毁链表;
2.数据结构类型为线性表,并采用链式存储结构存储;
3. #define ElemType int //链表数据域数据类型规定为整型
#define STATUS int
#define FAILURE 0
#define SUCCESS 1
typedef struct LNode
{ //定义链表结点及链表
ElemType data;
struct LNode *next;
}LNode,*LinkList;