//头文件
#ifndef DOUBLELIST_H
#define DOUBLELIST_H
#include
using namespace std;
template
class LinkNode{
public:
T data;
LinkNode
* link;
LinkNode
* prev;
LinkNode(const T item, LinkNode
* str=NULL, LinkNode
* ptr=NULL){ data = item; link = str; prev = ptr; } }; template
class doubleList{ private: static int count ; LinkNode
* head; LinkNode
* tail; LinkNode
* currPos; LinkNode
* position; bool seek(const T x);//查找与给定值相同的节点 public: doubleList(); ~doubleList(); void setValue(); bool deleteAim(const T x);//删除与给定值相同的节点 void clear(); void print(); int length(); }; template
int doubleList
::length() { return count; } template
int doubleList
::count = 0; template
void doubleList
::print() { LinkNode
* p = head; int i = length(); while (i) { cout << p->data << " "; p = p->link; i--; } } template
doubleList
::doubleList() { //默认构造函数 } template
doubleList
::~doubleList() { clear(); } template
void doubleList
::setValue() { T data; cin >> data; if (head == NULL) { head = new LinkNode
(data); head->link = head; //头结点的prev=NULL; head->prev = NULL; currPos = head; tail = head; count++; } else { LinkNode
* p = currPos; p->link = new LinkNode
(data); p = p->link; p->prev = currPos; //循环链表的尾指针应该指向头指针 p->link = head; currPos = p; tail = p; count++; } } template
bool doubleList
::seek(const T x) { LinkNode
* p = head; int i = length(); while (i) { if (p->data == x) { position = p; return true; } p = p->link; i--; } return false; } template
bool doubleList
::deleteAim(const T x) { if (seek(x)) { position->link->prev = position->prev; position->prev->link = position->link; delete position; count--; return true; } return false; } template
void doubleList
::clear() { LinkNode
* p = head; while (count) { p = p->link; delete head; head = p; count--; } } #endif //主函数 #include"DoubleList.h" int main(int argc, char argv[]) { doubleList
list; int count; cout << "输入你需要的链表长度,并初始化:"; cin >> count; for (int i = 0; i < count; i++) { list.setValue(); } list.print(); int number; cout << "输入你要删除的数:"; cin >> number; list.deleteAim(number); list.print(); return 0; }