C++ 双向链表

来源:互联网 发布:数据库彩票遗漏表设计 编辑:程序博客网 时间:2024/06/03 21:46

Node.cpp

/*
 * Node.cpp
 *
 *  Created on: 2013年12月27日
 *      Author: Administrator
 */


#include "Node.h"


namespace std {


Node::Node(int& value) {
// TODO Auto-generated constructor stub
  this->value = value;
}


Node::~Node() {
// TODO Auto-generated destructor stub
}
void Node::setValue(int& val){
   this->value = val;
}
int Node::getValue() const{
return this->value;
}
void Node::setNext(Node *nt){
this->next = nt;
}
Node* Node::getNext() const{
return this->next;
}
void Node::setPrev(Node* pv){
this->prev = pv;
}
Node* Node::getPrev() const{
return this->prev;
}
} /* namespace std */


Node.h

/*
 * Node.h
 *
 *  Created on: 2013年12月27日
 *      Author: Administrator
 */


#ifndef NODE_H_
#define NODE_H_


namespace std {


class Node {
private:
int value;
Node *next;
Node *prev;
public:
Node(int& value);
virtual ~Node();
void setValue(int& val);
int getValue() const;
    void setNext(Node *nt);
    Node* getNext() const;
    void setPrev(Node *prev);
    Node* getPrev() const;
};


} /* namespace std */


#endif /* NODE_H_ */


LinkList.cpp

/*
 * LinkList.cpp
 *
 *  Created on: 2013年12月27日
 *      Author: Administrator
 */


#include "LinkList.h"


namespace std {
int  LinkList::size() const{
 return this->ssize;
}


Node* LinkList::insert(int val){
//Node nd = this->insert(tail,val);
//Node *nd = new Node(val);
if(head == NULL)  tail = head = new Node(val);
else{
Node *prev = tail;
tail->setNext(new Node(val));
tail =  tail->getNext();
tail->setPrev(prev);
}
++ssize;
return tail;
}
LinkList::LinkList() {
// TODO Auto-generated constructor stub
   ssize = 0;
   head = tail =  NULL;
}
Node* LinkList::get(int index){
if(index >= this->size()) return NULL;
Node *tmp = tail;
int i = 0;
while(tmp != NULL){
if(i++ == index) break;
        tmp = tmp->getPrev();
}
    return tmp;
}
void LinkList::forwardtravel(){
Node *curr = head;
while(curr != NULL){
cout<<"forward:"<< curr->getValue()<<endl;
curr = curr->getNext();
}
}
void LinkList::backwardtravel(){
Node *curr = tail;
while(curr!=NULL){
cout<<"backward:"<<curr->getValue()<<endl;
curr = curr->getPrev();
}
}
LinkList::~LinkList() {
// TODO Auto-generated destructor stub


Node *curr = head;
while(curr != NULL){
Node *tmp = curr->getNext();
delete curr;
curr = tmp;
}
cout<<"链表元素被逐个销毁完成"<<endl;
}


} /* namespace std */


LinkList.h

/*
 * LinkList.h
 *
 *      Created on: 2013年12月27日
 *      Author: Administrator
 */


#ifndef LINKLIST_H_
#define LINKLIST_H_
#include "Node.h"
#include <iostream>
namespace std {


class LinkList {
/*************************
* 一个头针像灯塔一样永远不动
* 一个尾针逐元素向后
*/
private:
Node *head;
Node *tail;
int ssize;
public:
Node* insert(int val);
Node* get(int index);
int  size() const;
void forwardtravel();
void backwardtravel();
LinkList();
virtual ~LinkList();
};


} /* namespace std */


#endif /* LINKLIST_H_ */


在gcc-c++-4.4.5编译通过



0 0
原创粉丝点击