单链表类:class Slist

来源:互联网 发布:成都企业网络推广 编辑:程序博客网 时间:2024/06/10 08:27
//单链表//内容:默认4个,增删6个,打印,查找#pragma once#include<iostream>#include<assert.h>using namespace std;typedef int DataType;//节点类,struct类默认公有struct SListNode{//构造函数和成员变量都是公有的SListNode* _next;DataType _data;//写了构造函数就不用BuyNode了,可以直接newSListNode(DataType x)//注意L是大写:_data(x),_next(NULL){}};//单链表类class Slist{typedef SListNode Node;public:Slist():_head(NULL),_tail(NULL)//方便尾插{}Slist(const Slist& s):_head(NULL),_tail(NULL){Copy(s);}~Slist(){Destory();}//Slist& operator=(const Slist& s)//传统写法//{//if(this != &s)//{////释放this,头尾置空否则为野指针,后面PushBack会出错//Destory();//////Copy(s);//}////自己给自己赋值,直接走这里,不走if语句//return *this;//}Slist& operator=(Slist s)//现代写法,拷贝构造没现代写法,因为没有带参的构造函数{swap(_head, s._head);swap(_tail, s._tail);return *this;}void Destory()//释放链表{//_head为空不进入while所以这里无需判定_head不为空Node* cur = _head;while(cur){Node* del = cur;cur = cur->_next;delete del;//Node* next = cur;//delete cur;//cur = next;}_head = _tail = NULL;}void Copy(const Slist& s){Node* cur = s._head;while(cur){PushBack(cur->_data);cur = cur->_next;}}void PushBack(DataType x);void PushFront(DataType x);void Insert(Node* pos, DataType x);//1.头插 2.随机void PopBack();void PopFront();void Erase(Node* pos);//1.头删 2.尾删 3.随机void Print();Node* Find(DataType x);private://是指向节点的指针SListNode*,不是指向单链表类的指针SlistSListNode* _head;SListNode* _tail;};void Slist::PushBack(DataType x){//1.空 2.非空if(_head == NULL){_head = _tail = new Node(x);}else{_tail->_next = new Node(x);_tail = _tail->_next;}}void Slist::PushFront(DataType x){//1.空 2.非空if(_head == NULL){_head = _tail = new Node(x);}else{Node* tmp = new Node(x);tmp->_next = _head;_head = tmp;}}void Slist::Insert(Node* pos, DataType x){//因为能指定位置,则至少有一个节点//1.头插 2.随机位置assert(pos);if(_head == pos){PushFront(x);}else{Node* prev = _head;while(prev->_next != pos){prev = prev->_next;}Node* tmp = new Node(x);prev->_next = tmp;tmp->_next = pos;}}void Slist::PopBack(){//1.空 2.1个 3.多个if(_head == NULL){return;}else if(_head == _tail){delete _tail;_head = _tail = NULL;}else{Node* prev = _head;while(prev->_next != _tail){prev = prev->_next;}delete _tail;_tail = prev;_tail->_next = NULL;}}void Slist::PopFront(){//1.空 2.1个 3.多个if(_head == NULL){return;}else if(_head == _tail){delete _head;_head = _tail = NULL;}else{Node* del = _head;_head = _head->_next;delete del;}}void Slist::Erase(Node* pos){//1.尾删 2.头删 3.随机assert(pos);if(pos == _tail){PopBack();}else if(pos == _head){PopFront();}else{Node* prev = _tail;while(prev->_next != pos){prev = prev->_next;}prev->_next = pos->_next;delete pos;}}SListNode* Slist::Find(DataType x)//这里不能写Node*因为typedef在类里面没在外面{Node* cur = _head;while(cur){if(cur->_data == x){return cur;}cur = cur->_next;}return NULL;}void Slist::Print(){Node* cur = _head;while(cur){cout<<cur->_data<<" ";cur = cur->_next;}cout<<endl;}

原创粉丝点击