顺序表排序插入

本人用的是一个比较简单的方法,跟昨天的代码相比,只要多一个for循环从头判断就行

头文件等代码:

#ifndef _SEQUENCELIST_H
#define _SEQUENCELIST_H 

#define SIZE       10
#define SUCCESS    10000
#define FAILURE    10001
#define TRUE       10002
#define FALSE      10003

typedef int ElemType;

struct SequenceList
{
	int length;
	ElemType *data;    
};

typedef struct SequenceList SeList;

int SequenceInit(SeList *l);
int SequenceInsrt(SeList *l, int p, ElemType e);
int SequenceTraverse(SeList l, void (*p)(ElemType));

功能子函数:

#include "SequenceList.h"
#include <stdlib.h>

int SequenceInit(SeList *l)
{
	if (NULL == l)     //入参判断
	{
		return FAILURE;
	}

	l->length = 0;
	l->data = (ElemType *)malloc(sizeof(ElemType) * SIZE);
	if (NULL == l->data)
	{
		return FAILURE;
	}

	return SUCCESS;
}

int SequenceInsrt(SeList *l, int p, ElemType e)
{
	int i, j;

	if (NULL == l || NULL == l->data)
	{
		return FAILURE;
	}
	if (p > l->length + 1 || l->length >= SIZE || p < 1)
	{
		return FAILURE;
	}
	
	int temp;
	for(j = 0; j < l->length ; j++ )
	{
		if(e < l->data[j])
		{
			temp = l->data[j];
			l->data[j] = e;\
			e = temp;
		}
			
	}
	for (i = 0; i < l->length - p + 1; i++)
	{
		l->data[l->length - i] = l->data[l->length - i - 1];
	}

	l->data[p - 1] = e;
	l->length++;

	return SUCCESS;
}

int SequenceTraverse(SeList l, void (*p)(ElemType))
{
	if (p == NULL)
	{	
		return FAILURE;
	}
	int i;

	for (i = 0; i < l.length; i++)
	{
		p(l.data[i]);
	}

	return SUCCESS;
}

主函数如下:

#include "SequenceList.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print(ElemType e)
{
	printf("%d ", e);
}


int main()
{
	int ret, i;
	SeList list;

	srand(time(NULL));

	ret = SequenceInit(&list);
	if (ret == SUCCESS)
	{
		printf("Init Success!\n");
	}
	else 
	{
		printf("Init Failure!\n");
	}

	for (i = 0; i < 8; i++)
	{
		ret = SequenceInsrt(&list, i + 1, rand() % 10);
		if (FAILURE == ret)
		{
			printf("Insert Failure!\n");
		}
		else
		{
			printf("Insert Success!\n");
		}
	}
	
	ret = SequenceTraverse(list, print);   //顺序表遍历
	if (ret == FAILURE)
	{
		printf("Traerse Failure!\n");
	}
	else
	{
		printf("Traverse Success!\n");
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42720703/article/details/81394170
今日推荐