#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
typedef int DataType;
struct ListNode
{
DataType _data;
ListNode* _next;
ListNode* _prev;
ListNode(const DataType x)
:_data(x)
, _next(NULL)
, _prev(NULL)
{}
};
class List
{
typedef ListNode Node;
public:
List()
:_head(NULL)
, _tail(NULL)
{}
/*~List()
{
clear();
}*/
List(const List&L)
:_head(NULL)
, _tail(NULL)
{
Node*cur = L._head;
while (cur)
{
PushBack(cur->_data);
cur = cur->_next;
}
}
void Swap(List L)
{
swap(_head, L._head);
swap(_tail, L._tail);
}
List &operator=(List L)
{
Swap(L);
return *this;
}
/*void clear()
{
Node*cur = _head;
while (cur)
{
Node* tmp = cur;
cur = cur->_next;
delete tmp;
}
_head = _tail = NULL;
}*/
void PushBack(DataType x)
{
if (_head == NULL)
{
_head = _tail = new Node(x);
}
else
{
Node*tmp = new Node(x);
_tail->_next = tmp;
tmp->_prev = _tail;
_tail = _tail->_next;
}
}
void PushFront(DataType x)
{
if (_head == NULL)
{
_head = _tail = new Node(x);
}
else
{
Node*tmp = new Node(x);
tmp->_next = _head;
_head->_prev = tmp;
_head = tmp;
}
}
void PopBack()
{
if (_head == NULL)
{
return;
}
else if (_head->_next == NULL)
{
delete _head;
_head = _tail = NULL;
}
else
{
Node*tmp = _tail->_prev;
delete _tail;
_tail = tmp;
_tail->_next = NULL;
}
}
void PopFront()
{
if (_head == NULL)
{
return;
}
else if (_head->_next == NULL)
{
_head = _tail = NULL;
}
else
{
Node*tmp = _head->_next;
delete _head;
_head = tmp;
tmp->_prev = NULL;
}
}
void Print()
{
Node* cur = _head;
while (cur)
{
cout << cur->_data << " ";
cur = cur->_next;
}
cout << endl;
}
Node* Find(DataType x)
{
Node*cur = _head;
while (cur)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->_next;
}
return NULL;
}
void Insert(Node*pos, DataType x)
{
assert(pos);
if (pos == _head)
{
PushFront(x);
return;
}
Node* tmp = new Node(x);
Node*prev = pos->_prev;
Node*next = pos;
prev->_next = tmp;
tmp->_prev = prev;
tmp->_next = next;
next->_prev = tmp;
}
void Reverse()//链表的逆置
{
Node*cur = _head;
swap(_head, _tail);
while (cur)
{
swap(cur->_next, cur->_prev);
cur = cur->_prev;
}
}
void Erase(Node*pos)
{
assert(pos);
if (pos == _head)
{
PopFront();
}
else if (pos == _tail)
{
PopBack();
}
else
{
Node*prev = pos->_prev;
Node*next = pos->_next;
prev->_next = next;
next->_prev = prev;
}
}
private:
Node*_head;
Node*_tail;
};
void test1()
{
List l1;
l1.PushBack(20);
l1.PushBack(2);
l1.PushFront(22);
ListNode*ret = l1.Find(20);
if (ret == NULL)
{
cout << "找不到" << endl;
}
else
{
cout << ret->_data << endl;
}
l1.Insert(ret, 19);
l1.PopBack();
l1.PopFront();
l1.Print();
l1.Reverse();
l1.Print();
l1.Erase(ret);
l1.Print();
}
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
using namespace std;
#include"Slist.h"
int main()
{
test1();
system("pause");
return 0;
}