#ifndef _linknode_h_
#define _linknode_h_
class Node {
private:
Node* pNext;
void* pData;
public:
Node(void* pData);
~Node();
bool equals(const Node& node) ;
Node* next();
void setNext(const Node& node);
void* data()const ;
};
class SingleLinkedList {
private:
Node* head;
Node* tail;
public:
SingleLinkedList();
~SingleLinkedList();
void push_front(void* data);
void push_back(void* data);
void remove(void* data);
void display();
};
#endif
---------------------
#include "link.h"
#include <iostream>
using namespace std;
int main()
{
int a=5,b=1,c=2,d=5,e=9;
Node n(&a);
Node n2(&b);
Node* n3=new Node(&a);
Node* n4=new Node(&d);
//cout<<n.equals(n)<<endl;
cout<<n4->equals(*n3)<<endl;
cout<<*(int*)(n.data())<<endl;
n.setNext(n3);
cout<< *(int*)(n.next()->data())<<"-------以上是测试Node--------"<<endl;
SingleLinkedList link ;
link.push_front(&a);
link.push_front(&b);
link.push_front(&e);
link.push_back(&c);
link.remove(&d);
link.display();
return 0;
}
Node::Node(void* pData):pData(pData),pNext(NULL)
{
}
Node::~Node()
{
}
bool Node::equals(const Node& node)
{
int* idata= (int*)pData;
int* ndata= (int*)(node.data());
if((*idata)==(*ndata))
return true;
else
return false;
}
void* Node::data()const
{
return pData;
}
void Node::setNext(const Node& node)
{
this->pNext=const_cast<Node*>(&node);
}
Node* Node::next()
{
return pNext;
}
SingleLinkedList::SingleLinkedList():head(0),tail(0)
{
}
SingleLinkedList::~SingleLinkedList()
{
Node* tmp=head;
while(tmp!=NULL){
tmp->~Node();
tmp = tmp->next();
}
}
void SingleLinkedList::display()
{
Node* tmp=head;
while(tmp!=NULL){
cout<< *(int*)(tmp->data())<<endl;
tmp = tmp->next();
}
}
void SingleLinkedList::push_front(void *data)
{
Node* node=new Node(data);
if(this->head==NULL)
{
this->head=node;
this->tail=node;
cout<<"在空链表中插入了个头结点"<<endl;
}
else{
node->setNext(*head);
this->head= node;
//cout<<"非空链表"<<endl;
}
cout<<"从前面插入一个结点"<<*(int*)data<<endl;
}
void SingleLinkedList::push_back(void* data)
{
Node* node=new Node(data);
if(this->tail==NULL)
{
this->head=node;
this->tail=node;
}
else{
this->tail->setNext(*node);
tail=node;
}
cout<<"从后面插入一个结点"<<*(int*)data<<endl;
}
void SingleLinkedList::remove(void* data)
{ //Node* currentData=new Node(data);隐式转化
Node* temp=this->head;
Node* preNode=NULL;
while(temp!=NULL)
{
if(temp->equals(data))
{
if(temp==this->head){
cout<<"不好, head结点"<<*(int*)temp->data()<<"要被删掉了"<<endl;
this->head=temp->next();
temp->~Node();
}else
{
preNode->setNext(*(temp->next()));
temp->~Node();
}
return;
}
preNode=temp;
temp=temp->next();
}
}