PTA题目:顺序表---插入结点

创建顺序表,在顺序表中插入一个结点。 顺序表结构定义如下:

typedef char ElemType;
typedef struct 
{
    
    
	ElemType data[MaxSize];
   	int length;
} SqList;

要求写出:

void DispList(SqList *L);  //输出顺序表,每个结点之间空格符间隔。
bool ListInsert(SqList *&L,int i,ElemType e);  //在顺序表第i个位置上插入一个结点,插入成功时,返回TRUE,否则返回FALSE.

函数接口定义

void InitList(SqList *&L);	//初始化线性表  .由裁判程序实现。
void DispList(SqList *L);  //输出顺序表,每个结点之间空格符间隔。
bool ListInsert(SqList *&L,int i,ElemType e);  //在顺序表第i个位置上插入一个结点,插入成功时,返回TRUE,否则返回FALSE.

裁判测试程序样例:

#include <stdio.h>
#include <malloc.h>
#define MaxSize 1000
typedef char ElemType;
typedef struct 
{
    
    
	ElemType data[MaxSize];
   	int length;
} SqList;
void InitList(SqList *&L);	//初始化线性表
void DispList(SqList *L);
bool ListInsert(SqList *&L,int i,ElemType e);

int main()
{
    
    
	SqList *L;
	ElemType e,ch;
	int i=1;
	InitList(L);
	while((ch=getchar())!='\n')
	{
    
    
		ListInsert(L,i,ch);  //在L的第i个元素位置上插入ch
		i++;
	}
	DispList(L);
	scanf("\n%d %c",&i,&ch);
	if ( ListInsert(L,i,ch))
			DispList(L);
}

/* 请在这里填写答案 */

输入样例:

在这里给出一组输入。例如:

abcdefghijk
5 X

输出样例:

在这里给出相应的输出。例如:

a b c d e f g h i j k 
a b c d X e f g h i j k 

分析

插入部分是个很基础的数组插入,首先从最后一个数字开始往后移,直到把第i个数字也移动完成。这里需要注意的是一个界限的问题,当i<1或者i比总长度加一还大,链表总长度已经达到MaxSize时,与题意想违背。应当去除这些情况。后面有一个格式问题,笔者也出过这个问题了,输出完毕后应该输出一次换行,因为每个样例要用到两次输出函数,这两次的输出值是分行的。

答案

bool ListInsert(SqList *&L,int i,ElemType e){
    
    
	int k;
    if(i < 1 || i > L->length+1|| L->length == MaxSize)return false;
	for(k=L->length;k>=i;k--){
    
    
		L->data[k]=L->data[k-1];
	}
	L->data[i-1]=e;
	L->length++;
	return true;
}
void DispList(SqList *L){
    
    
	int t;
	for(t=0;t<L->length;t++){
    
    
		printf("%c ",L->data[t]);
	}
    printf("\n");
}

如果觉得博主写得不错的话,就点个赞或者关注吧!

猜你喜欢

转载自blog.csdn.net/qq_45619909/article/details/109140385