#include <iostream>
using namespace std;
class List
{
public:
List()
{
init();
}
List ( const List & rhs )
{
init();
*this = rhs;
// operator= ( rhs );
}
const List & operator= ( const List &rhs )
{
if ( this != &rhs )
{
Node *oldh = rhs.head;
while ( oldh->next != NULL )
{
oldh = oldh->next;
back ( oldh->data );
}
}
}
~List()
{
delete head;
}
int size() const
{
return theSize;
}
bool isEmpty() const
{
return size() == 0;
}
void push ( int x )
{
Node *h = new Node;
h->data = x;
h->next = head->next;
head->next = h;
theSize++;
}
void back ( int x )
{
Node *h = head;
Node *p = new Node;
while ( h->next != NULL )
{
h = h->next;
}
p->data = x;
h->next = p;
}
void pop () const
{
if ( !isEmpty() )
{
Node *n = head;
cout << n->next->data << endl;
}
else
cout << "Empty" << endl;
}
void print() const
{
Node *h = head;
while ( h->next != NULL )
{
h = h->next;
cout << h->data << " ";
}
cout << endl;
}
void swap ( int index )
{
int i = 0;
if ( size() > index )
{
Node *h = head;
Node *p = new Node;
Node *n = new Node;
while ( i != index )
{
i++;
p = h;
h = h->next;
}
n = h->next;
h->next = n->next;
p->next = n;
n->next = h;
}
}
void clear()
{
while ( head->next != NULL )
{
head = head->next;
delete head;
}
theSize = 0;
}
private:
struct Node
{
int data;
Node *next;
Node ( int d = 0, Node *n = NULL )
: data ( d ), next ( n ) {}
};
private:
int theSize;
Node *head;
void init()
{
theSize = 0;
head = new Node;
}
};
单链表
最新推荐文章于 2023-05-06 22:43:40 发布