用C++实现一个单向循环链表,从控制台输入整型数字,存储在单项循环链表中,实现了求链表大小。
不足之处,还望指正!
复制代码 代码如下:
// TestSound.cpp : 定义控制台应用程序的入口点。
//实现单向循环链表
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//定义链表一个节点的结构体
template <class T>
struct NODE
{
T data;//节点的数据域
NODE* next;//节点的指针域
};
//自定义链表容器(含有的方法与C++不尽相同)
template <class T>
class MyList
{
public:
//构造函数,初始化一个头结点,data为空,next指向第一个节点
MyList()
{
phead = new NODE<T>;
phead->data = NULL;
phead->next = phead;
}
//析构函数,将整个链表删除,这里采用的是正序撤销
~MyList()
{
NODE<T>* p = phead->next;
while (p != phead)
{
NODE<T>* q = p;
p = p->next;
delete q;
}
delete phead;
}
//复制构造函数
MyList(MyList& mylist)
{
NODE<T>* q = mylist.phead->next;
NODE<T>* pb = new NODE<T>;
this->phead = pb;
while (q != mylist.phead)
{
NODE<T>* p = new NODE<T>;
p->data = q->data;
p->next = phead;
pb->next = p;
pb = p;
q = q->next;
}
}
//返回list表的大小
int get_size();
//将用户输入的integer数据,插入list表中
void push_back();
//将list表中的元素输出
void get_elements();
private:
NODE<T>* phead;
};
//返回list表的大小
template <class T>
int MyList<T>::get_size()
{
int count(0);
NODE<T>* p = phead->next;
while (p != phead)
{
count ++;
p = p->next;
}
return count;
}
//将用户输入的integer数据,插入list表中
template <class T>
void MyList<T>::push_back()
{
int i;
cout << "Enter several integer number, enter ctrl+z for the end: "<< endl;
NODE<T>* p = phead;
while (cin >> i)
{
NODE<T>* q = new NODE<T>;
p->next = q;
q->data = i;
q->next = phead;
p = q;
}
}
//将list表中的元素输出
template<class T>
void MyList<T>::get_elements()
{
NODE<T>* q = phead->next;
while (q != phead)
{
cout << q->data << " ";
q = q->next;
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
MyList<int> mylist;
mylist.push_back();
MyList<int> mylist2(mylist);
mylist.get_elements();
mylist2.get_elements();
cout << endl << mylist.get_size() << endl;
return 0;
}