您的位置:首页 > 其它

顺序结构实现线性表的基本操作

2015-09-06 08:33 609 查看
<pre name="code" class="cpp">    #include <stdio.h>
#include <stdlib.h>
typedef int Elementype;
#define maxsize 10
typedef struct {
Elementype data[maxsize];
int last;

}List;
int find (Elementype x,List *ptr)
{
int i=1;
while (i<ptr->last && ptr->data[i]!=x)   ///从i=1开始不断往后查找
i++;
if (i>ptr->last)
{
printf ("Not found\n");
return -1;
}
else
printf("The element you want to find in List is %dth\n",i);
return 0;
}
void Insert (Elementype x,int i,List *ptr)
{
int j;
if (ptr->last==maxsize)
{
printf ("List is full!\n");
return;
}
if (i<1 || i>ptr->last+2)
{
printf ("Error:i\n");
return;
}
for (j=ptr->last;j>=i;j--)
ptr->data[j+1]=ptr->data[j];  ///将data[i+1]~data
向后移
ptr->data[i]=x;
ptr->last++;
return;
}
void Delete  (int i,List *ptr)
{
int j;
if (i<1 || i>ptr->last+1)  ///检查空表及删除位置的合法性
{
printf ("Not found %dth element\n",i);
return;
}
for  (j=i+1;j<=ptr->last;j++)
ptr->data[j-1]=ptr->data[j];   ///将data[i+1]~data
向前移
ptr->last--;
return;
}
void Scanf_List (List *p)          ///输入单链表数据
{
int i;
for (i=1;i<=p->last;i++)
scanf ("%d",&p->data[i]);
}
void Printf_List (List*p)  ///遍历单链表
{
int i;
for (i=1;i<=p->last;i++)
printf ("%d ",p->data[i]);
printf ("\n");
}
int main  ()
{
List n;
printf ("Please input the lenth of List:\n");
scanf("%d",&n.last);
printf ("Please input elements of List:\n");
Scanf_List(&n);
Printf_List(&n);
while (1)
{
int m;
printf ("Please choose the operate\n");
printf ("1:Find\n2:Insert\n3:Delet\n");
scanf ("%d",&m);
switch (m)
{
case 1:
{
int data;
printf ("Please input the element you want to find\n");
scanf ("%d",&data);
find(data,&n);
}break;
case 2:
{
int i,h;
printf ("Please input the element and position you want to insert\n");
scanf ("%d %d",&h,&i);

Insert(h,i,&n);
printf ("Insert element is %d\n",h);
Printf_List(&n);
}break;
case 3:
{
int a;
printf ("Please input  position of the element you want to delete\n ");
scanf ("%d",&a);
Delete(a,&n);
printf ("The element was deleted is %d\n",n.data[a]);
Printf_List(&n);
}break;
}
}
return 0;
}



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