自己寫雙鏈表

<pre name="code" class="cpp">#include<iostream>
using namespace std;
typedef struct student{
	int data;
	struct student *pre;
	struct student	*next;
}Dlist;
Dlist *Crt_dlist(){
	Dlist *head,*p,*next;
	int x,cycle = 1;
	head  = new Dlist;
	p = head;
	while(cycle){		
			cout	<<	"請輸入"	<<	endl;
			cin	>>	x;
			if(x != 0 ){
				next	=	new Dlist;
				next->data =	x;
				next->pre =p;
				p->next = next;
				p = next;
			}else{
				cycle =0;
			}
		}
	head =	head->next;
	head->pre =NULL;
	p->next =  NULL;
	return head;
}
void Insert_dlist(Dlist *L,int e){
	Dlist *p=L,*ptemp;
	ptemp =new Dlist;
	ptemp->data = e;
	while(ptemp->data >	p->data&&p->next	!=	NULL)
		p=p->next;
	if(ptemp->data	<=	p->data){//at the head 
		if(p==L){
			ptemp	->next = L;
			L->pre =	ptemp;
			ptemp->pre = NULL;
			L = ptemp;
		}else{//in the middle			
			ptemp->next=p;
			p->pre->next =ptemp;
			ptemp->pre = p->pre;
			p->pre = ptemp;
		}
	}else{//at the tail
		p->next = ptemp;
		ptemp->next = NULL;
		ptemp->pre =  p;
	}
	return ;
}
void Travert_dlist(Dlist *L){
	while(L!= NULL){
		cout	<<	L->data<<"-";
		L = L->next;
	}
}
void Del_dlist(Dlist *L,int e){
	Dlist *p;
	p	=	L;
	while(p->data	!=	e	&&	p->next	!= NULL)
		p = p->next;
	if(p->data	==	e){
		if(p == L){//the positon of e is head;
			L = L->next;
			L->pre = NULL;
			delete p;
		}else if(p->next ==NULL){//at the tail
			p->pre->next =NULL;
			delete p;
		}else{//in the middle
			p->next->pre = p->pre;
			p->pre->next =p->next;
		}	
	}
}
int Locat_e_dlist(Dlist *L,int e){
		int j=1;
		Dlist *p = L;
		while(p->data != e && p->next != NULL){
			p = p->next;
			j++;
		}
		if(p->data == e){
			if(p == L){
				return 1;
			}else{
			return j;
			}
		}else{
			cout << "不存在該數" << endl;
			return 65535;
		}
}
int Get_len_dlist(Dlist *L){
	int len=1;
	while(L!= NULL){
		len++;
		L = L->next;
	}		
	return len;
}
void Sort_dlist(Dlist *L){
	Dlist *p,*pnext,*ptemp;
	int data;
	for(p = L;p->next != NULL;p = p->next){
		ptemp = p;
		for(pnext =p->next;pnext != NULL;pnext = pnext->next){
			if(p->data < pnext->data){
				ptemp = pnext;
			}
		}
		if(ptemp != p){
			data = p->data;
			p->data = ptemp->data;
			ptemp->data =	data;
		}
	}
}
void main(){
	Dlist *head;
	int x;
	head =	Crt_dlist();	
	Travert_dlist(head);
	cout<<"*******************"<<endl;
	Insert_dlist(head,10);
	cout<<"*******************"<<endl;
	Travert_dlist(head);
	cout << "請輸入刪除那個數?";
	cin >> x;
	Del_dlist(head,x);
	cout<<"*******************"<<endl;
	Travert_dlist(head);
	cout << "請輸入要定位的數";
	cin >> x;
	Locat_e_dlist(head,x);
	cout<<"*******************"<<endl;
	cout << Locat_e_dlist(head,x);
	cout<<"*******************"<<endl;
	cout << "the length of the dlist:"<<Get_len_dlist(head)<<endl;
	cout<<"*******************"<<endl;
	Sort_dlist(head);
	cout << "after select sort:" <<endl;	
	Travert_dlist(head);
}


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