#include<iostream>
using namespace std;
struct Node
{
int data;
Node * next;
Node(int x):data(x),next(NULL){}
};
class LinkedList
{
private:
Node * head;
int length;
public:
LinkedList();//构造
~LinkedList();
void Insert(int data,int pos);//在位置pos插入新结点
int Length();
void Delete(int pos) ;//删除pos处结点
void print();//遍历
void Reverse();//逆置
void clear();
};
LinkedList::LinkedList():head(NULL),length(0)
{
}
LinkedList::~LinkedList()
{
clear();
}
int LinkedList::Length()
{
return length;
}
void LinkedList::Insert(int data, int pos)
{
if(pos<0||pos>length)
{
cout<<"error!";
return;
}
Node * newNode=new Node(data);
length++;
if(pos==0)//插入头结点
{
newNode->next=head;
head=newNode;
return;
}
Node *p1=head,*p2=p1;//插入位置在p1和p2之间,p1是p2前一结点
for(int i=0;i<pos;i++)
{
p1=p2;
p2=p2->next;
}
newNode->next=p2;
p1->next=newNode;
}
void LinkedList::Delete(int pos) //删除pos处结点
{
if(pos<0||pos>length)
{
cout<<"error";
return;
}
if(pos==0)
{
length--;
Node * tmp=head;
head=head->next;
delete tmp;
}
Node *p1=head,*p2=p1;
for(int i=0;i<pos;i++)
{
p1=p2;
p2=p2->next;
}
length--;
p1->next=p2->next;
delete p2;
}
void LinkedList::Reverse()
{
if(head==NULL)
{
return;
}
Node * cur,*curnext;
cur=head->next;
head->next=NULL;
while(cur!=NULL)
{
curnext=cur->next;
cur->next=head;
head=cur;
cur=curnext;
}
}
void LinkedList::print()
{
if (length==0)
{
cout<<"链表为空";
return;
}
Node*tmp=head;
cout<<"print:\n";
while(tmp!=NULL)
{
cout<<tmp->data<<"-->";
tmp=tmp->next;
}
cout<<"NULL\n";
}
void LinkedList::clear()
{
Node *tmp;
while(length)
{
tmp=head;
head=head->next;
delete tmp;
length--;
}
head=NULL;
}
int main()
{
LinkedList l1;
l1.Insert(1,0);
l1.Insert(2,0);
l1.Insert(3,1);
l1.Insert(4,3);
l1.print();
l1.Reverse();
l1.print();
l1.clear();
l1.print();
return 0;
}