zoukankan      html  css  js  c++  java
  • 关于线性表的线性表的实现(顺序结构)

    学习了数据结构后对线性表有了更好的了解,所谓线性表有两种实现方法,一种是用顺序结构,一种是用链式结构。具体说来就是用动态数组与链表的方式来实现。

    这便是数据结构的两种储存方式,顺序存储结构与链式存储结构,同时也是数据结构研究的存储结构的具体体现,因此线性表的实现对于初步学习数据结构的我们有着重要的意义。

    这篇博客用的是动态数组实现线性表。

    利用了c++里面的关键词new  进行内存动态分配  以致插入数据时不会溢出

    同时为了增加程序的可读性,将ok定义为1,error定义为0,等等一些;

    主函数中的几个步骤为输入,输出。

    //线性表的实现(顺序结构)
    #include<iostream>
    #include <vector>
    #include <iomanip>
    #define maxsize 100;
    #define OK 1;
    #define ERROR 0;
    #define OVERFLOW -2;
    using namespace std;
    typedef int Status;
    typedef int ElemType;
    int a[10]={0,12,15,16,56,78,46,12,32,78};
    typedef struct//线性表的构建 
    {
        ElemType *elem;
        int length;
    }Sqlist;
    Status initList(Sqlist &l)//线性表的初始化
    {
        l.elem=new ElemType[15];
        if(!l.elem) exit(-2);
        l.length=0;
        return OK;
    }
    Status getelem(Sqlist &l,int i,ElemType &e)//顺序表的取值 
    {
    	if(i<1||i>l.length)  return ERROR;
    	e=l.elem[i-1];
    	
    	return 1;
    }
    int locateElem(Sqlist &l,ElemType &e)//顺序表的 
    {
    	for(int i=0;i<l.length;i++)
    	  if(e==l.elem[i]) 
    	  {
    	  	cout<<"这个数据是第"<<i+1<<"位"<<endl;
    		  return i+1;
    	   } 
    	  else  ;
    	  cout<<"没有这个数据
    ";
    	  return 0;
    }
    int  listinsert(Sqlist &l,int i,int e)
    {
    	if(i<1||i>l.length)
    	{
    		cout<<"输入错误"<<endl;
    		return 0;
    	} 
    	else {
    		for(int j=l.length-1;j>=i-1;j--)
    		 l.elem[j+1]=l.elem[j];
    		l.elem[i-1]=e;
    	}
    	l.length++;
    	for(int j=0;j<l.length;j++)
    	 cout<<l.elem[j]<<" ";
    	cout<<endl;
    }
    int main()
    {
    	int e,n,w,s;
    	Sqlist l;
    	initList(l);
    	l.elem=a;
    	l.length=10;
    	cout<<"输入位数:n="; 
    	cin>>n;
    	if(!getelem(l,n,e))  cout<<"输入错误"<<endl;
    	else cout<<"第"<<n<<"位是"<<e<<endl;
    	cout<<"输入数据:";
    	cin>>w;
    	locateElem(l,w);
    	cout<<"输入插入次序:";
    	cin>>s;
    	cout<<endl<<"输入插入数据:";
    	cin>>e;
    	listinsert(l,s,e);
    
    	return 0;
    }


  • 相关阅读:
    哈夫曼树
    MUI
    mui.init方法配置
    js中如何把字符串转化为对象、数组示例代码
    ( 转 )超级惊艳 10款HTML5动画特效推荐
    ( 转 ) 关于微信公众号,你不知道的15个小技巧
    h5预加载代码
    css3常用动画样式文件move.css
    iphone微信 h5页音乐自动播放
    sshpass: 用于非交互的ssh 密码验证
  • 原文地址:https://www.cnblogs.com/young-for-you/p/7286910.html
Copyright © 2011-2022 走看看