马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
//函数原型说明
Status InitList(LinkList &L);
void CreateListTail(LinkList &L,int n);
Status GetElem(LinkList L,int i,ElemType &e);
int printf(LinkList L);
Status GetMidNode(LinkList L,ElemType &e);
int ListLength(LinkList L);
Status InitList(LinkList &L) //创造一个空的单链表
{
L=(LinkList)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next=NULL;
return OK;
}//InitList
void CreateListTail(LinkList &L,int n) //按照尾插法随机插入n个元素
{
LinkList p,r;
int i;
srand(time(0));
L=(LinkList)malloc(sizeof(LNode));
r=L;
for(i=1;i<=n;i++)
{
p=(LinkList)malloc(sizeof(LNode));
p->data=rand()%100+1;
r->next=p;
r=p;
}
r->next=NULL;
}
int ListLength(LinkList L) //单链表的长度
{
int i=0;
LinkList p=L->next;
while(p)
{
p=p->next;
i++;
}
return i;
}
Status GetElem(LinkList L,int i,ElemType &e) //返回第i个元素
{
if(!L)
return ERROR;
LinkList p;
int j;
p=L->next;
while(p&&j<i)
{
p=p->next;
j++;
}
if(!p||j>i)
return ERROR;
e=p->data;
return OK;
}//GetElem
int printf(LinkList L) //输出单链表的元素
{
if(!L)
return ERROR;
LinkList p;
p=L->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
return OK;
}//output
Status GetMidNode(LinkList L,ElemType &e)//查找中间元素
{
if(!L)
return ERROR;
LinkList mid,search;
mid=search=L->next;
while(search->next->next!=NULL)
{
mid=mid->next;
search=search->next->next;
}
e=mid->data;
return OK;
}
void main()
{
LinkList L ;
int i,n=6;
int s;
ElemType e;
InitList(L);
cout<<"请输入您选择的项目:"<<"1.创建链表\n"<<"2.查看链表\n"<<"3.链表长度\n"<<"4.中间元素\n"<<"0.退出\n";
while(s!='0')
{
cin>>s;
switch(s)
{
case 1: CreateListTail(L,n); break;
case 2: printf(L); break;
case 3: ListLength(L); break;
case 4: GetMidNode(L,e); break;
case 0: exit(0);break;
}
}
}
|