用C++完成單向輪回鏈表的處理辦法。本站提示廣大學習愛好者:(用C++完成單向輪回鏈表的處理辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是用C++完成單向輪回鏈表的處理辦法正文
用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;
}