1. 程式人生 > >雙鏈表--簡單操作

雙鏈表--簡單操作

以下是某同學的成績,通過雙鏈表實現增加,刪除,查詢等功能。

#include<iostream>
using namespace std;

class Node{
public:
    int data;
    Node* next,*prior;
};

class List{
public:
	List();
	List(int a[],int n);
	~List();
	int length();
	int Get(int i);
	int Locate(int x);
	void Insert(int i,int x);
	int Delete(int i);
	void Print();
private:
	Node*first;
};
List::List(){
	first=new Node;
	first->next=NULL;
	first->prior=NULL;

}
List::List(int a[],int n){   //頭插法新建連結串列
    Node*s;
	int i;
	first=new Node;
	first->next=NULL;
	for(i=0;i<n;i++)
	{
	s=new Node;
	s->data=a[i];
	s->next=first->next;
	first->next=s;
	}
}
void List::Print(){     //遍歷連結串列
     Node*p;
    p=first->next;
	while(p!=NULL)
	{
	cout<<p->data<<"  ";
	p=p->next;  
	}
}


int List::length(){     //求表長
	    Node*p; int count;
		p=first->next;
		count=0;
		while(p!=NULL)
		{
		p=p->next;
		count++;
		}
		return count;
}
int List::Get(int i){   //按位查詢
	   Node*p;int count;
		p=first->next;
		count=1;
		while(p!=NULL&&count<i)
		{
		p=p->next;
		count++;	
		}
		if(p==NULL) throw"位置";
		else return  p->data;
	}


int List::Locate(int x){   //按值查詢
	  Node*p;int count;
		p=first->next;
		count=1;
		while(p!=NULL)
		{
		if(p->data==x) return count;
		p=p->next;
		count++;	
		}
		return  0;
}

void List::Insert(int i,int x){   //插入
	  Node*p,*s;int count;
		p=first; 
		count=0;
		while(p!=NULL&&count<i-1)
		{
		p=p->next;
		count++;		
		}
		if(p==NULL) throw"位置";
		else{
       s=new Node;
	   s->data=x;
	   s->next=p->next;
	   p->next=s;
		}
}
	int List::Delete(int i)    //刪除
	{
	Node *q,*p; int x;
	p=first;
		p = first;

		while (i-- > 1)    //因為p是從first開始走,走一次i減一次。但最後是要在i前面的,所以大於一
		p= p->next;
		if(p==NULL||p->next==NULL) throw"位置";
		else{
		q = p->next;
		x=q->data;
		if (p->next != NULL){
			if(q->next!=NULL)
		q->next->prior = p;

			else{
		p->next=NULL;
	    p->next = q->next;
		delete q;
		q = NULL;
		return x;
		}
	}
		 p->next = q->next;
		 delete q;
		 q = NULL;
		return x;
	}}

	List::~List()   //析構
	{
	Node*q;
	while(first!=NULL)
	{
	q=first;
	first=first->next;
	delete q;
	}
	}


	int main()
	{
     int n,i,p,num,numb,se,x,a[100];
	 cout<<"請輸入需要建立雙鏈表的結點個數:"<<endl;
	 cin>>n;
	 cout<<"請輸入需要建立雙鏈表的結點:"<<endl;
     for(i=0;i<n;i++)
	 {
	   cin>>a[i];
	 }
	List student(a,n);  
	cout<<"列印連結串列值如下:"<<endl;
    student.Print();  
    cout<<endl<<"請輸入插入結點的位置和值;"<<endl; cin>>p>>num;  
    student.Insert(p,num); 
	cout<<"列印連結串列值如下:";
    student.Print();  
    cout<<endl<<endl<<"請輸入要刪除結點的位置:"<<endl; cin>>numb;
	cout<<"it's  "<<student.Delete(numb)<<endl<<"列印連結串列值如下:"<<endl;  
    student.Print();  
    cout<<endl<<endl<<"請輸入要查詢結點的位置:"<<endl; cin>>se;
		cout<<"列印連結串列值如下:"<<student.Get(se)<<endl;  
    cout<<endl<<endl<<"請輸入要查詢結點的數值:"<<endl;   cin>>x;
	cout<<"它的位置是:"<<student.Locate(x)<<endl;
	return 0;
	}


實驗結果如圖所示: