面向对象第四次作业参考代码

第一题:数组

#include 

const int MAXSIZE = 20;

class List{
public:
	List()
	{
		arr = new int[MAXSIZE];   //Allocation the space
		length = 0;               //the length of current array
		cout<<"Please input the data into the array:"<>*(arr + i);
			length ++;
		}
	}
	~List()
	{
		delete []arr;
	}
	void Insert(int i,int x);   //Insert a data into the array
	void Delete(int i);         //Delete a data from the array
	int Find(int x);            //Search a data from the array return the position of the data
	void Show();                //Print the data to SCR
private:
	int *arr;
	int length;
};

void List::Insert(int i,int x)
{
	if(i < 1 || i > length + 1)
	{
		cout<<"插入位置非法!"<= q; --p)
		*(p + 1) = *p;   //插入位置及之后的数据后移
	*q = x;  //插入x
	++length;  //长度加1
	return;
}

void List::Delete(int i)
{
	if( i < 1 || i > length)
	{
		cout<<"删除位置非法!"<

第二题:链表

#include  
  
struct Arr  
{  
    int data;  //数据
    struct Arr *next;  //链表指针  
}; 

class Link{
private:
	Arr *head;
public:
	Link();
	void Create();
	void Insert(int n,Arr *Insdata);
	void Delete(int m);
	void Show();
	int Find(int x);
	static int num;
};

int Link::num = 0;  //静态变量初始化

Link::Link()  //构造函数
{
	head = new Arr;
	head->next = NULL;
}

void Link::Create()  //创建链表
{
	Arr *p1,*p2;
	p1 = p2 = new Arr;
	cout<<"Please input the data:"<>p1->data;
	while(p1->data != 0)
	{
		if(head->next == NULL)
		{
			head->next = p1;
		}
		else
		{
			p2->next = p1;
		}
		p2 = p1;
		num++;
		p1 = new Arr;
		cin>>p1->data;
	}
	p2->next = NULL;
	return;
}

void Link::Show()  //显示链表的数据
{
	Arr *p;
	p = head->next;
	cout<<"the Link's data:"<data<<"  ";
		p = p->next;
	}
	cout<next;
	p2 = p1->next;
	cout<<"Please input the data that you want to insert:"<>Insdata->data;
	p1->next = Insdata;
	Insdata->next = p2;
	num++;
}

void Link::Delete(int m)//删除第m个数据元素
{
	Arr *p1,*p2;
	p1 = head;
	for(int i = 1;i < m;i++)
		p1 = p1->next;
	p2 = p1->next;
	p1->next = p2->next;
	delete p2;
	num--;
}

int Link::Find(int x)//查找数据为x的节点的位置
{
	Arr *p;
	int n = 1;
	p = head->next;
	while(p != NULL)
	{
		if(p->data == x)
			return n;
		else
			p = p->next;
		n++;
	}
	return -1;
}

void main()
{
	Link obj;
	obj.Create();
	obj.Show();
	Arr *p = new Arr;;
	int n,m;
	cout<<"Please input the position that you want insert data:"<>n;
	if(n > obj.num + 1 || n < 1)
	{
		cout<<"The position is invalid!"<>n;
	if(n > obj.num || n < 1)
	{
		cout<<"The position is invalid!"<>n;
	m = obj.Find(n);
	if(m == -1)
		cout<<"Not Found!"<


 

你可能感兴趣的:(C++)