c++实现单链表(构造函数 拷贝函数 前插 后插 运算符重载 冒泡排序以及逆置)

来源:互联网 发布:mac的ppt怎么调16:9 编辑:程序博客网 时间:2024/06/05 17:22
#pragma once#include<iostream>using namespace std;typedef int DataType;class SListNode{public: SListNode(DataType x) :_x(x), _next(NULL), _pre(NULL) { } friend class SList;private: DataType _x; SListNode *_next; SListNode *_pre; };class SList{public: SList() :_head(NULL), _tial(NULL) { } SList(SList &s) {  SListNode *cur = s._head;  while (cur)  {   PushBack(cur->_x);   cur = cur->_next;  } } void PushBack(DataType x) {  SListNode *cur = _head;  if (_head == NULL)  {   _head = new SListNode(x);   _tial = _head;  }  else  {   SListNode *tmp = new SListNode(x);   _tial->_next = tmp;   tmp->_pre = _tial;   _tial = _tial->_next;     } } void PopBack() {  if (_head == NULL)   return;  else if (_head==_tial)  {   delete[]_head;   _head = NULL;   _tial = NULL;   return;  }  SListNode *tmp = _tial->_pre;  delete[]_tial;  tmp->_next = NULL;  _tial = tmp; } void PushFront(DataType x) {  if (_head == NULL)  {   _head = new SListNode(x);   _tial = _head;   return;  }  SListNode *tmp = new SListNode(x);  tmp->_next = _head;  _head->_pre = tmp;  _head = tmp; } void PopFront() {  if (_head == NULL)   return;  else if (_head->_next==NULL)  {   delete[]_head;   _head = NULL;   _tial = NULL;  }  else  {   SListNode *tmp = _head->_next;   delete[]_head;   _head = tmp;   _head->_pre = NULL;  } } void insert(SListNode *pos,DataType x) {  if (pos == _tial)  {   PushBack(x);  }  else  {   SListNode *tmp = new SListNode(x);   SListNode *next = pos->_next;   pos->_next = tmp;   tmp->_next = next;   tmp->_pre = pos;   next->_pre = tmp;  } } void BubbleSort() {  SListNode *p = _head;  SListNode *pend = NULL;  while (p->_next != pend)  {   SListNode *cur = _head;   for (; cur->_next != pend; cur = cur->_next)   {    if (cur->_x > cur->_next->_x)     swap(cur->_x, cur->_next->_x);   }   pend = cur;  } }  void Reverse() {  if (_head == _tial&&_head==NULL)  {   return;  }  SListNode *left = _head;  SListNode *right = _tial;    while (left->_next!=right&&left!=right)  {   swap(left->_x, right->_x);   left = left->_next;   right = right->_pre;  }  swap(left->_x, right->_x); } void Clear() {  SListNode *cur = _head;  while (cur)  {   SListNode *p = cur->_next;   delete[]cur;   cur = p;  }  _head = NULL;  _tial = NULL; } SList(SList & s) {  SListNode *cur = s._head;  while (cur)  {   PushBack(cur->_x);   cur = cur->_next;  } } SList &operator=(SList &s) {  SList tmp(s);  swap(_head, tmp._head);  swap(_tial, tmp._tial);  return *this; } ~SList() {  Clear(); } void PrintList() {  SListNode *cur = _head;  while (cur)  {   cout << cur->_x << "->";   cur = cur->_next;  }  cout << "NULL" << endl; }private: SListNode *_head; SListNode *_tial;};


0 0
原创粉丝点击