这是一个 DLinkedList 实现,使用 addFront() 将 int 类型的元素添加到其中,但使用 front() 未检索到它。没有显示错误。不知道为什么??这是完整的实现。代码在 xCode4.5 上运行。
int main(int argc, const char * argv[])
{
DLinkedList listOne;
if(listOne.empty()){
cout<<"Empty";
}
const int num=23;
listOne.addFront(num);
//Here 0 is returned from front(), while it should be 23;
cout<<listOne.front()<<endl;
return 0;
}
//Node Defination
class DNode { // doubly linked list node
private:
int elem; // node element value
DNode* prev; // previous node in list
DNode* next; // next node in list
friend class DLinkedList; // allow DLinkedList access
};
class DLinkedList { // doubly linked list
public:
DLinkedList(); // constructor
~DLinkedList(); // destructor
bool empty() const; // is list empty?
const int front() const; // get front element
const int back() const; // get back element
void addFront(const int e); // add to front of list
void addBack(const int e); // add to back of list
void removeFront(); // remove from front
void removeBack(); // remove from back
private: // local type definitions
DNode* header; // list sentinels
DNode* trailer;
protected: // local utilities
void add(DNode* v, const int e); // insert new node before v
void remove(DNode* v); // remove node v
};
void listReverse(DLinkedList& L) { // reverse a list
DLinkedList T; // temporary list
while (!L.empty()) { // reverse L into T
int s = L.front(); L.removeFront();
T.addFront(s);
}
while (!T.empty()) { // copy T back to L
int s = T.front(); T.removeFront();
L.addBack(s);
}
}
void DLinkedList::remove(DNode* v) { // remove node v
DNode* u = v->prev; // predecessor
DNode* w = v->next; // successor
u->next = w; // unlink v from list
w->prev = u;
delete v;
}
void DLinkedList::removeFront() // remove from font
{ remove(header->next); }
void DLinkedList::removeBack() // remove from back
{ remove(trailer->prev); }
// insert new node before v
void DLinkedList::add(DNode* v, const int e) {
DNode* u = new DNode; u->elem = e; // create a new node for e
std::cout<<u->elem<<std::endl;
u->next = v; // link u in between v
u->prev = v->prev; // ...and v->prev
v->prev->next = v->prev = u;
}
void DLinkedList::addFront(const int e) // add to front of list
{
add(header->next, e);
}
void DLinkedList::addBack(const int e) // add to back of list
{ add(trailer, e); }
DLinkedList::~DLinkedList() { // destructor
while (!empty()) removeFront(); // remove all but sentinels
delete header; // remove the sentinels
delete trailer;
}
DLinkedList::DLinkedList() { // constructor
header = new DNode; // create sentinels
trailer = new DNode;
header->next = trailer; // have them point to each other
trailer->prev = header;
std::cout<<"DLinkedListConstructor"<<std::endl;
}
bool DLinkedList::empty() const // is list empty?
{ return (header->next == trailer); }
const int DLinkedList::front() const // get front element
{ return header->next->elem; }
const int DLinkedList::back() const // get back element
{ return trailer->prev->elem; }