69,369
社区成员
发帖
与我相关
我的任务
分享
typedef struct Node *List;
List ReverList(List L) //单链表反转函数 无表头
{
List curPos,nexPos,prePos; //分别是当前的、下一个、前一个
prePos=NULL;
curPos=L;
nexPos=L->next;
while(nextPos!=NULL)
{
curPos->next=prePos;
prePos=curPos;
curPos=nexPos;
nexPos=nexPos->next;
}
curPos->next=prePos;
return curPos;
}
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW -2
#define ERROR 0
#define LIST_INIT_SIZE 100
typedef int ElemType;
typedef int Status;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
/////////创建链表
Status CreateLst(LinkList &L,int n)
{
int i;
L=(LinkList)malloc(sizeof(LNode));
if(!L) {exit(OVERFLOW);}
L->next=NULL;
printf("输入数据:\n");
for(int i=0;i<n;++i)
{
LinkList p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
return OK;
}
///逆置操作
Status OrderLst(LinkList &L)
{
LinkList p,q,r;
p=L->next;
//p->next=NULL;
//L->next=p;
q=p->next;
p->next=NULL;
while(q->next){
r=q->next;
q->next=p;
p=q;
q=r;
}
q->next=p;
L->next=q;
printf("逆序输出\n");
return OK;
}
///输出元素
Status PrintLst(LinkList L)
{
if(L==NULL){printf("链表未创建!\n");exit(1);}
printf("链表的元素为:");
while(L->next)
{
L=L->next;
printf("%d ",L->data);
}
printf("\n");
return OK;
}
////////主函数
int main()
{
int n=0;
LinkList Lst;
printf("请输入链表的个数:");
scanf("%d",&n);
CreateLst(Lst,n);
PrintLst(Lst);
OrderLst(Lst);
PrintLst(Lst);
system("pause");
}