#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Node
{
ElemType data;
Node *next;
}ListNode;
class List
{
public:
List();
ListNode* CreateList(ListNode *&root,int n);
ListNode* Locate(ListNode *root,int i,ElemType &e);
bool Insert(ListNode *&root,int i,ElemType e); //第i个元素前插入元素
bool Delete(ListNode *&root,int i,ElemType &e);
void Display(ListNode *root);
void Review(ListNode *&root); //带头结点的链表逆置
private:
ListNode *root;
};
List::List()
{
root=new ListNode;
root->next=NULL;
}
ListNode* List::CreateList(ListNode *&root,int n)
{
//创建n个结点,
ListNode *last=new ListNode;
int i,key;
last=root;
last->next=NULL;
cout<<"请依次输入节点数据"<<endl;
for(i=0;i<n;++i)
{
ListNode *newNode=new ListNode;
cin>>key;
newNode->data=key;
newNode->next=NULL;
newNode->next=last->next;
last->next=newNode;
last=newNode;
}
return root;
}
void List::Display(ListNode *root)
{
while (root->next)
{
cout<<root->next->data<<" ";
root=root->next;
}
}
ListNode* List::Locate(ListNode *root,int n,ElemType &e)
{
if(n<=0) return root;
for(int i=0;i<n;++i)
{
root=root->next;
if(!root)
return NULL;
}
e=root->data;
return root;
}
bool List::Insert(ListNode *&root,int i,ElemType e)
{
if(i<0) return false;
int d;
ListNode *current=Locate(root,i-1,d);
if(!current) return false;
ListNode *newNode=new ListNode;
newNode->data=e;
newNode->next=NULL;
newNode->next=current->next;
current->next=newNode;
return true;
}
bool List::Delete(ListNode *&root,int i,ElemType &e)
{
if(i<1) return false;
ElemType temp;
ListNode *current=Locate(root,i-1,temp);
ListNode *del=current->next;
current->next=del->next;
e=del->data;
cout<<e<<"所为删除节点"<<endl;
delete del;
return true;
}
void List::Review(ListNode *&root)
{
ListNode *pre=new ListNode;
ListNode *p=new ListNode;
p=NULL;
pre=root->next;
ListNode *current=pre->next;
for(current;current!=NULL;current=current->next)
{
pre->next=p;
p=pre;
pre=current;
}
pre->next=p;
root->next=pre;
}
int main()
{
List a;
ListNode *root=new ListNode;
cout<<"要输入几个数据"<<endl;
int n,temp;
ElemType e,y;
cin>>n;
root=a.CreateList(root,n);
cout<<"创建成功,链表所含节点"<<endl;
a.Display(root);
cout<<endl;
cout<<"删除函数测试,请输入删除节点的信息(第几个)"<<endl;
cin>>temp;
if(!a.Delete(root,temp,e))
cout<<"删除错误!"<<endl;
cout<<"删除后的链表: ";
a.Display(root);
cout<<endl;
cout<<"增加函数测试,请输入要插入的位置和节点的值"<<endl;
cin>>temp>>y;
if(!a.Insert(root,temp,y))
cout<<"插入错误!"<<endl;
cout<<"插入后的链表"<<endl;
a.Display(root);
cout<<endl;
cout<<"链表逆置测试"<<endl;
a.Review(root);
a.Display(root);
system("pause");
return 0;
}