您的位置:首页 > 其它

1.2静态链表

2015-09-25 17:01 393 查看
#include<iostream>
#define MAXSIZE 100
using namespace std;
typedef struct
{
int x;
int next;
}SNode;

typedef struct
{
SNode sp[MAXSIZE];
int SL;
}StList,*PStList;

//静态链表初始化
PStList Creat_StList(void)
{
//创建一静态链表,入口参数无
PStList PL;
PL=(PStList)malloc(sizeof(StList));
if(PL)
{
PL->SL=-1;
//PL->sp[0].next=-1;
}
return PL;
}
//求静态链表的长度
int Length_StList(StList L)
{
return L.SL+1;
}
//静态链表的检索操作
int Location_StList(StList L,int x)
{
int i=0;
while(i<L.SL&&L.sp[i].x!=x)
i++;
if(i>=L.SL)  return 0;//查找失败
else return (i+1);
}
//静态链表的插入操作
int Insert_StList(PStList PL,int x)
{
//在静态链表的((第i个元素之前))插入x//;
if(!PL)
{
cout<<"表不存在!";
return (-2);
}
if(PL->SL>=MAXSIZE)
{
cout<<"表溢出!";
return (-1);
}
/*if(i<1||i>PL->SL+1)
{
cout<<"插入位置不合法!";
return 0;
}*/
PL->sp[PL->SL+1].x=x;
PL->sp[PL->SL+1].next=-1;

if(PL->SL>=0)
PL->sp[PL->SL].next=PL->SL+1;
PL->SL++;
return 1;    // 插入成功
}
//静态链表的删除操作
int Delete_StList(PStList PL,int i)
{
//删除静态链表第i个元素
int j,k;
if(!PL)
{
cout<<"表不存在!";
return (-2);
}
if(PL->SL>=MAXSIZE)
{
cout<<"表溢出!";
return (-1);
}
if(i<1||i>PL->SL)
{
cout<<"删除位置不合法!";
return 0;
}
k=PL->sp[0].next;
for(j=0;j<i-1;j++)
k=PL->sp[j].next;

PL->sp[j].next=PL->sp[k].next;

return 1;    // 删除成功
}

int josephus(PStList josephus_StList,int s,int m)
{
//入口参数为已存在的链表头指针,起始位置s,报数到m
int i,s1,w;
if(!josephus_StList)
{
cout<<"表中无元素!";
return 0;
}

cout<<"输出约瑟夫序列:"<<endl;

for(i=josephus_StList->SL;i>0;i--)
{
s1=(s1+m-1)%i;  //出列元素下标
w=josephus_StList->sp[s1].x;
cout<<w<<"\t";
Delete_StList(josephus_StList,s1+1);
}
return 1;
}
int main()
{
PStList H=Creat_StList();
int i;
for(i=0;i<10;i++)
Insert_StList(H,9-i);

for(i=0;i<10;i++)
cout<<H->sp[i].x<<" ";
//josephus(H,1,2);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: