Using C++ to achieve a one way circular linked list solution

  • 2020-04-02 00:57:18
  • OfStack

Using C++ to achieve a one-way circular linked list, from the console input integer number, stored in a single circular linked list, the realization of the size of the linked list.
Shortcomings, but also hope to correct!

//Testsound.cpp: defines the entry point for the console application.
//Implement a one-way loop linked list
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//Defines the structure of a node in a linked list
template <class T>
struct NODE
{
 T data;//The data domain of the node
 NODE* next;//The pointer field of the node
};
//Custom linked list containers (with different methods than C++)
template <class T>
class MyList
{
public:
 //Constructor, initializes a header, data is null, and next points to the first node
 MyList()
 {
  phead = new NODE<T>;
  phead->data = NULL;
  phead->next = phead;
 }
 //Destructor, delete the entire list, here is the use of positive order undo
 ~MyList()
 {
  NODE<T>* p = phead->next;
  while (p != phead)
  {
   NODE<T>* q = p;
   p = p->next;
   delete q;
  }
  delete phead;
 }
 //Copy constructor
 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;
  }
 }
    //Returns the size of the list table
 int get_size();

 //Inserts the integer data entered by the user into the list table
 void push_back();

 //Output the elements in the list table
 void get_elements();
 private:
 NODE<T>* phead;
};
//Returns the size of the list table
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;
}
//Inserts the integer data entered by the user into the list table
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;
 }
}
//Output the elements in the list table
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; 
}


Related articles: