/*--------------------------------------------------------------------------------
* Project: TList.h
* Name: zwp
* Date: 2013.4
*--------------------------------------------------------------------------------*/
#ifndef TLIST_H_
#define TLIST_H_
#include <iostream>
typedef int ListType; // 元素类型
class List
{// 循环链表
private:
struct Node
{
ListType data;
Node* next;
Node(ListType value, Node* link = 0)
{
data = value;
next = link;
}
};
typedef Node* NodePointer;
NodePointer head;
public:
List();
~List();
List(const List& list);
const List& operator=(const List& list);
bool empty(void)const;
void insert(ListType value);
void deleted(void);
friend std::ostream& operator<<(std::ostream& os, const List& list);
};
#endif
/*------------------------------------------------------------------------
* Project: TList.cpp
* Name: zwp
* Date: 2013.4
*-------------------------------------------------------------------------*/
#include <cassert>
#include "TList.h"
List::List()
:head(0)
{ }
List::~List()
{
if(!empty())
{
List::NodePointer ptr = head;
List::NodePointer prev;
while(ptr != 0)
{
prev = ptr->next;
delete ptr;
ptr = prev;
}
}
}
bool List::empty(void)const
{
return (head == 0);
}
List::List(const List& list)
{
if(!empty())
{
head = new List::Node(list.head->data);
List::NodePointer ptr = list.head->next;
List::NodePointer prev = head;
while(ptr != 0)
{
prev->next = new List::Node(ptr->data);
ptr = ptr->next;
prev = prev->next;
}
}
}
const List& List::operator=(const List& list)
{
if(this != &list)
{
this->~List(); // 销毁之前的链表
if(list.empty())
head = 0;
else
{
head = new List::Node(list.head->data);
List::NodePointer ptr = list.head->next;
List::NodePointer prev = head;
while(ptr != 0)
{
prev->next = new List::Node(ptr->data);
prev = prev->next;
ptr = ptr->next;
}
}
}
return *this;
}
void List::insert(ListType value)
{
List::NodePointer prev = head;
List::NodePointer ptr;
ptr = new List::Node(value);
assert(ptr != 0);
if(head == 0)
head = ptr;
else
{
while(prev->next != 0)
prev = prev->next; // 找到链表末尾
prev->next = ptr; // 将新的节点插入
}
}
void List::deleted(void)
{
if(empty())
std::cerr <<"The List is empty..."<<std::endl;
else
{
List::NodePointer ptr = head;
head = head->next;
delete ptr;
}
}
std::ostream& operator<<(std::ostream& os, const List& list)
{
//assert(!list.empty());
List::NodePointer ptr = list.head->next;
while(ptr != 0)
{
std::cout <<ptr->data<<" ";
ptr = ptr->next;
}
return os;
}
/*-------------------------------------------------------------------------------
* Project: Test.cpp
* Name: zwp
* Date: 2013.4
*-------------------------------------------------------------------------------*/
#include <iostream>
#include "TList.h"
int main(void)
{
List list1;
for(int index = 1; index < 10; index ++)
list1.insert(index);
list1.deleted();
List list2(list1);
std::cout <<list2<<std::endl;
List list3 = list2;
std::cout <<list3<<std::endl;
std::cout <<list1<<std::endl;
system("pause");
return 0;
}