刪除數組中一樣的元素

#include<iostream>
using namespace std;

class ARR 
{
	private:
		int size;
		int buff[100];
	public:
		ARR(int a[],int length);
		void show();
		void delsame();
};

ARR::ARR(int a[],int length)
{
	int i;
	size=length;
	for(i=0;i<size;i++)
	{
		buff[i]=a[i];
	};
}

void ARR::show()
{
	int i;
	for(i=0;i<size;i++)
		cout<<buff[i];
	cout<<endl;
}


void ARR::delsame()
{
	int i,j;
	for(i=0;i<size;i++)
	{
		if(buff[i-1]==buff[i])
		{
			for(j=i;j<size;j++)
				buff[j]=buff[j+1];
			size--;
			i--;
		};
	};
}

int main(){
	int arr[16]={1,2,2,3,4,4,5,6,6,7,8,8,8,9,10,10};
	ARR x(arr,16);
	x.show();
	x.delsame();
	x.show();
	return 0;
}
自己動手總是錯誤百出

用鏈表動態儲存數據:

#include<iostream>
using namespace std;


struct node             //節點的聲明
{
	int data;
	node *next;
};


class ARR               //類的聲明
{
private:
	node * head;
	int size;
public:
	ARR();
	void creat();
	void show();
	void delsame();
};
ARR::ARR()               //構造函數
{
	head=new node;
	size=0;
}

void ARR::creat()        //創建鏈表儲存數字串
{
	node *p1,*p2;
	int mark,item;
	int n=1;
	cout<<"請輸入鏈表結束標誌(僅數字):"<<endl;
	cin>>mark;
	cout<<"請輸入第一個數字:"<<endl;
	cin>>head->data;
	p1=head;
	p2=head;
	while(item!=mark)
	{
		p1=new node;
		cout<<"請輸入第"<<n<<"個數字"<<endl;
		cin>>item;
		if(item==mark)
			break;
		p1->data=item;
		p2->next=p1;
		p2=p1;
		n++;
	};
	size=n;
	p2->next=NULL;
}


void ARR::show()            //輸出
{
	node *p;
	p=head;
	while(p!=NULL)
	{
		cout<<p->data<<endl;
		p=p->next;
	};
	cout<<"長度是"<<size<<endl;
}

void ARR::delsame()
{
	int i;
	node *p1,*p2;
	p1=head;
	p2=head->next;
	for(i=0;i<size-1;i++)
	{
		if(p1->data==p2->data)
		{
			p2=p2->next;
			p1->next=p2;
			size--;
			i--;
		}
		else
		{
			p1=p1->next;
			p2=p2->next;
		}
	};
}



int main ()
{
	ARR  x;
	x.creat();
	x.show();
	x.delsame();
	x.show();
	return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章