设为首页 加入收藏

TOP

DS之顺序表实现乱序输入顺序输出
2015-07-24 10:23:08 来源: 作者: 【 】 浏览:1
Tags:顺序 实现 输入 输出

顺序表的实例有很多,在学其他的编程语言时,肯定都学过要求输入一串乱序的数字,要求进行排序,实现升序或降序输出。今天就来用顺序表实现乱序输入,顺序输出(升序)。

实现上述的功能需要用到的顺序表的基本操作有0基本操作前的准备,1初始化顺序表,6向顺序表插入数据元素。

自己只需写一个排序的函数,排序函数的代码为:

//排序函数
void paixu(SqList &L)
{
   for(int i=0;iL.elem[i])
		  {
	            int temp;
	            temp=L.elem[i];
	            L.elem[i]=L.elem[j];
                 L.elem[j]=temp;
             }
       }
   }
}

然后只需在主函数中定义一个顺序表,乱序输入一些数据元素,调用排序函数,然后遍历输出排序后的顺序表的所有数据元素。整个代码为:

#include 
using namespace std;
#include 
#include 
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100 
#define LISTINCREMENT  10
typedef int ElemType;
typedef int Status;
typedef struct
{
	ElemType *elem;//存储空间基址
	int length;//当前长度
	int listsize;//当前分配的存储容量
}SqList;//定义了一个结构体类型,并命名为Sqlist
//1初始化顺序表
Status InitList(SqList &L)
{
     L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
	 if(!L.elem)
     { 
          exit(OVERFLOW);
     }          
	L.length=0;//长度为0
	L.listsize=LIST_INIT_SIZE;
 	return OK;
}
//6向顺序表插入数据元素	
Status ListInsert(SqList &L,int i, ElemType e)
{
	if(i<1||i>L.length+1)
	{
		return ERROR;
	}
	if (L.length>=L.listsize)
	{
        ElemType *newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT )*sizeof(ElemType));
        if(!newbase) 
		{
		   exit(OVERFLOW);
		}
        L.elem=newbase;
        L.listsize+=LISTINCREMENT;
	}
    ElemType *q=&(L.elem[i-1]);
    ElemType *p;
	for(p=&(L.elem[L.length-1]);p>=q;--p)
	{
		*(p+1)=*p;
	}
	*q=e;
	++L.length;
	return OK;
}
//排序函数
void paixu(SqList &L)
{
   for(int i=0;iL.elem[i])
		   {
	            int temp;
	            temp=L.elem[i];
	            L.elem[i]=L.elem[j];
                L.elem[j]=temp;
           }
       }
   }
}
int main()
{ 
    SqList La;
    InitList(La);
    cout<<"请输入La中数据的个数:";
    int na;
    ElemType e;
    cin>>na;
    for(int i=1;i<=na;i++) 
    {
	  cin>>e;
	  ListInsert(La,i,e);
    }
    paixu(La);
	cout<<"排序后的La的数据元素为:"<

输入顺序表的元素个数为:10

乱序输入的数据元素为:3 2 7 9 0 1 4 8 6 5

输出的结果为:

\

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Aerospike-Architecture系列之数.. 下一篇数据库调优教程(一)前言&慢..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·微服务 Spring Boot (2025-12-26 18:20:10)
·如何调整 Redis 内存 (2025-12-26 18:20:07)
·MySQL 数据类型:从 (2025-12-26 18:20:03)
·Linux Shell脚本教程 (2025-12-26 17:51:10)
·Qt教程,Qt5编程入门 (2025-12-26 17:51:07)