顺序表的查找/删除/插入

遇到的问题  malloc、realloc的用法

realloc:(类型 *)realloc(原来的内存地址,新的大小(*类型));

    指针的问题:要深刻理解指针,指针也是一个变量,在函数传递参数的过程中,作为参数来讲,传递的也是值。这个值就是指针本身的内容,即指针指向的地址。而

不是传的指针。所以指针作为函数形参是一定要注意! 

代码:

#include <iostream>

#include <cstdlib>

using namespace std;

int Maxsize=10;

typedef struct SeqListNode

{

	int data;

	int len;

}*SeqList;

void createSeqList(SeqList &seqTable)

{

	

	 seqTable=(struct SeqListNode *)malloc(Maxsize*sizeof(struct SeqListNode));

	 if(seqTable)

	 {

	 seqTable->len=0;

	 for(int i=0;i<Maxsize;i++)

	 {

		 seqTable[seqTable->len++].data=i;

	 }

	 }

	 cout<<"create success"<<endl;

}



void insertNode(SeqList &seqTable,int elem,int i)

{

	if(i<0)

		cout<<"i can not less than 0"<<endl;

	else

	{

		seqTable=(struct SeqListNode *)realloc(seqTable,(Maxsize+1)*sizeof(struct SeqListNode));

		if(seqTable)

		{

		for(int j=seqTable->len;j>(i+1);j--)

			seqTable[j].data=seqTable[j-1].data;

	    seqTable[i+1].data=elem;

	    seqTable->len++;

		}

	}

}



int findElem(SeqList &seqTable,int elem)

{

	int i;

	for( i=0;i<seqTable->len;i++)

	{

		if(seqTable[i].data==elem)

			return i;

	}

	if(i>=seqTable->len)

	{

		cout<<"can not find the elem"<<endl;

		return -1;

	}

}



void deleteElem(SeqList &seqTable,int elem)

{

	int i;

	int temp;

	for( i=0;i<seqTable->len;i++)

	{

		if(seqTable[i].data==elem)

		{

			temp=seqTable[i].data;

			for(int j=i;j<seqTable->len-1;j++)

			{

				seqTable[j].data=seqTable[j+1].data;

			}

			seqTable->len--;

			break;

		}

	}

	if(i>=seqTable->len)

	{

		cout<<"can not find the elem"<<endl;

	}

}



void displaySeqList(SeqList &seqTable)

{

	int i=0;

	while(i<seqTable->len)

	{

		cout<<seqTable[i].data<<" ";

		i++;

	}

	cout<<endl;

	cout<<endl;

}



int main()

{

	SeqList seqTable=NULL;

	createSeqList(seqTable);  //create seqTable;

	cout<<"display:";

	displaySeqList(seqTable);



    insertNode(seqTable,12,3);  //insert node;

    cout<<"after insert:";

	displaySeqList(seqTable);



	cout<<"6 position: "<<findElem(seqTable,6)<<endl<<endl;;  //find element position;



	deleteElem(seqTable,7);

	cout<<"after delete:";

	displaySeqList(seqTable);



	free(seqTable);

	return 0;

}

运行结果:

顺序表的查找/删除/插入

你可能感兴趣的:(删除)