您的位置:首页 > 理论基础 > 数据结构算法

循环双链表删除第一个值为x的结点

2017-09-26 21:40 127 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐