用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;
}