1. 程式人生 > >迴圈雙鏈表刪除第一個值為x的結點

迴圈雙鏈表刪除第一個值為x的結點

#include <iostream>
using namespace std;
int const NONE = 0;
int const DONE = 1; 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class List;

//結點 
class Node{
	friend class List;
public:
	Node(double data, Node *prev = NULL, Node *next = NULL){
		this->data = data;
		this->prev = prev;
		this->next = next;
	}
private:
	double data;
	Node *prev;
	Node *next;
};

//迴圈雙鏈表 
class List{
public:
	List();
	~List();
	bool isEmpty(){ return length == 0; }
	void addNode(double data);  //新增結點 
	void print();          
	void deleteX(double x);     //刪除指定數值節點 
private:
	int length;
	Node *head;
	Node *end;
	Node *p;
};
List::List(){
	length = 0;
	//頭結點存結點數量 
	head = new Node(0);
	end = head;
	p = NULL;
}
List::~List(){
	Node *temp = NULL;
	Node *count = head->next;
	head->next = NULL;
	while(count){
		temp = count;
		count = count->next;
		delete temp;
	}
	length = 0;
	head = NULL;
	end = NULL;
	temp = NULL;
	p = NULL;
}
//新增結點 
void List::addNode(double data){
	Node *newNode = new Node(data);
	length ++;
	head->data = length;
	if(head == end){
		end = newNode;
		head->next = newNode;
		head->prev = end;
		end->prev = head;
		end->next = head;
	}else{
		end->next = newNode;
		newNode->prev = end;
		end = newNode;
		end->next = head;
	}
	newNode = NULL;
}
void List::print(){
	Node *temp = head->next;
	if(length == 0){
		cout<<"空"<<endl;
	}else{
		while(temp != head && temp != NULL){
			cout<<temp->data<<'\t';
			temp = temp->next;
		}
		cout<<endl;
		temp = NULL;
	}
}
void List::deleteX(double x){
	//判斷是否為空 
	if(isEmpty()){
		cout<<"無法執行刪除操作!"<<endl;
	}else{ 
		int count = NONE;  //記錄是否找到結點 
		p = head->next;
		while(p != head && p != NULL){
			if(p->data == x){
				count = DONE;
				length --;
				head->data = length;
				if(length == 0){
					head->prev = NULL;
					head->next = NULL;
					end = head;
					delete p;
					p = NULL;
				}else{
					p->next->prev = p->prev;
					p->prev->next = p->next;
					delete p;
					p = NULL;
				}
				break;
			}else{
				p = p->next;
			}
		}
		if(count == NONE){
			cout<<"未找到要刪除的x值!"<<endl;
		}
	}
}

//測試 
int main(int argc, char** argv) {
	double x;
	List list;
	list.addNode(5);
	list.addNode(8);
	list.addNode(9);
	list.addNode(5);
	list.addNode(9);
	list.addNode(14);
	list.print();
	cout<<"請輸入要刪除的x值:"<<endl;
	cin>>x;
	list.deleteX(x);
	list.print();
	cout<<"請輸入要刪除的x值:"<<endl;
	cin>>x;
	list.deleteX(x);
	list.print();
	cout<<"請輸入要刪除的x值:"<<endl;
	cin>>x;
	list.deleteX(x);
	list.print();
	return 0;
}