数据结构,线性表,顺序表基础。

 

1.线性表

              线性表特征:

             

  1. 对非空表,a0是表头,无前驱
  2. a(n-1)是表尾,无后继
  3. 其他的都有ai前驱a(i-1)与后继a(i+1)。

 2、顺序结构存储方式是线性表存储的一种方式,主要体现形式为数组。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 10
typedef int data_t;

typedef struct list{
    data_t data[SIZE];//保存数据的数组(表)
    data_t last;//保存尾元素的下标

} seqlist,*seqlist_t;

//创建顺序表
seqlist* create_selist()
{
		seqlist_t head =(seqlist*) malloc (sizeof(seqlist));
			if(NULL==head) return NULL;
			memset(head->data,0,sizeof(head->data));
			head->last=-1;//表示空
			return head;//返回表头
}
//判空:
	int seqlist_is_empty(seqlist* head)
{
		if(NULL==head) return -1;
		return (-1==head->last)?1:0;
}
//判满
int seqlist_is_full(seqlist * head)
{
	if(NULL==head) return -1;
		return (SIZE==head->last+1)?1:0;
}
//求元素个数
int seqlist_is_num(seqlist * head)
{
	if(NULL==head) return -1;
		return (head->last+1);
}
//指定位置增加元素
int seqlist_is_install(seqlist * head,int pos,data_t val)
{
	if(NULL==head) return -1;//指向为空
    if(1==seqlist_is_full(head)) return -2; //线性表已经满了
    
    #if 1
    int i=seqlist_is_num(head);//1、数量初始化i
    for ( i ; i>pos; i--)//此处i可以等于也可以不等于pos
    {
        head->data[i]=head->data[i-1];
    }
    #else   
    int i=head->last;//2、下标初始化i 
    for ( i ; i>=pos; i--)
    {
        head->data[i+1]=head->data[i];
    }
    #endif
    

    head->data[pos]=val;
    head->last++;
    return 0;
}
//指定位置删除元素
int seqlist_is_del(seqlist * head,int pos)
{
	if(NULL==head) return -1;//指向为空
    if(1==seqlist_is_empty(head)) return -2; //线性表为空
    for (int i=pos;i<head->last; i++)
    {   
        head->data[i]=head->data[i+1];
    }
    head->last--;
    return 0;
}
//修改指定位置元素
int seqlist_is_change(seqlist * head,int pos,int val)
{
	if(NULL==head) return -1;//指向为空
    if(1==seqlist_is_empty(head)) return -2; //线性表为空
        head->data[pos]=val;
    return 0;
}
//查找元素
int seqlist_is_find(seqlist * head,int val)
{
	if(NULL==head) return -1;//指向为空
    if(1==seqlist_is_empty(head)) return -2; //线性表为空
    for (int i = 0; i<=head->last; i++)
    {
        if(head->data[i]==val)
        {
            return i;
        }
    }
    return -1;
}
//输出数组
int seqlist_is_print(seqlist *head)
{  
    if(NULL==head) return -1;//线性表为空
    for (int i = 0; i <seqlist_is_num(head); i++)
        {
           printf("%d ",head->data[i]);
        }
        puts("");
}

int main()
{
    seqlist * phead=create_selist();
    seqlist_is_install(phead,0,1);
    seqlist_is_install(phead,1,2);
    seqlist_is_install(phead,2,3);
    seqlist_is_install(phead,3,4);
    seqlist_is_install(phead,4,5);
    seqlist_is_install(phead,5,6);
   //seqlist_is_install(phead,2,1233);
    seqlist_is_change(phead,3,11111);
    int k=seqlist_is_find(phead,3);

    if(k>-1)
    {
        printf("找到位置为%d\n",k);
    }
    else
    {
        printf("不存在要找的数\n");
    }
    
   // seqlist_is_del(phead,3);
    seqlist_is_print(phead);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_52119661/article/details/132348016