用C++實現單向迴圈鏈表的解決方案

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.