Create the source file named: Slist.cpp.
#include "Slist.h" int main () {Test (); System ("pause"); return 0;}
Create a header file named: Slist.h.
#ifndef __slish_h__#define __slist_h__#include<iostream>using namespace std;typedef int datatype;class slistnode{ friend class slist;public: slistnode (datatype x) :_next (NULL) , _data (x) {}private: DataType _data; SlistNode* _next;}; Class slist{public: slist () :_head ( NULL) , _tail (NULL) {} slist (const slist& s) :_head (NULL) , _tail (NULL) { slistnode* cur = s._head; while (cur) { this-> Pushback (cur->_data); cur = cur->_next; } } Slist& operator= (const slist& s) { slist tmp; slistnode* pcur = _head; while (pcur) { slistnode* del = pcur; pcur = pcur->_next; delete del; del = NULL; } tmp = s; SlistNode* cur = s._head; while (cur) { this->pushback (Cur->_data); cur = cur->_next; } } ~slist () { SlistNode* cur = _head; while&nbSP; (cur) { SlistNode* del = cur; cur = cur->_next; delete del; del = NULL; } } void pushback (datatype x) { //0 1 if (_head == null) { _head = new slistnode (x); _tail =&nbSp;_head; } else { /*_tail->_next = new slistnode (x); _tail = _tail->_next; */ SlistNode* cur = New slistnode (x); _tail->_next = cur; _tail = cur ; } } void Popback () { if (_head == _tail) &Nbsp; { if (_head == null) { return; } else { delete _head; _head = null; _ tail = null; } } else { slistnode* cur = _head; while (cur) { SlistNode* _next = cur->_next; if (_next == _tail) { delete _tail; _tail = null; _tail = cur; _tail->_next = null; } cur = cur->_next; } } } void printslist () { if (_head== null) { return; } else { slistnode* cur = _head; while (cur) { cout << cur->_data < < " "; cur = cur->_next; } cout << endl; } }private: slistnode* _head; slistnode* _tail;}; Void test () { slist s; s.pushback (1); s.pushback (2); s.pushback (3); s.pushback (4); s.pushback (5); s.printslist (); s.popback (); s.printslist ();} #endif //__slist_h__
This article is from the "C language 100-200 Prime" blog, please be sure to keep this source http://10740184.blog.51cto.com/10730184/1747325
The "C + +" uses the class to implement the one-way single-linked list pushback (), tail-delete popback (), Print printslist ().