#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Student_data
{
int data;
struct Student_data *next;
}*PSD,SD;
PSD creat_list();
int length_list(PSD );
bool sort_list(PSD );
bool insert_list(PSD );
bool traverse_list(PSD );
bool delete_list(PSD );
int main()
{
PSD pHead = NULL;
pHead = creat_list();
int len = length_list(pHead);
cout<<"链表长度为: "<<length_list(pHead)<<endl;
traverse_list(pHead);
insert_list(pHead);
sort_list(pHead);
traverse_list(pHead);
delete_list(pHead);
traverse_list(pHead);
return 0;
}
PSD creat_list()
{
int len;
cout<<"请输入需要输入数据的个数: ";
cin>>len;
PSD pHead = (PSD)malloc(sizeof(SD));
PSD pTail = pHead;
pTail->next = NULL;
if(pHead == NULL)
{
cout<<"错误 !";
exit(-1);
}
for(int i=0;i<len;i++)
{
PSD pNew = (PSD)malloc(sizeof(SD));
if(pNew == NULL)
{
cout<<"错误 !";
exit(-1);
}
cout<<"请输入第 "<<i+1<<"个数据: ";
cin>>pNew->data;
pTail->next = pNew;
pNew->next = NULL;
pTail = pNew;
}
return pHead;
}
int length_list(PSD pHead)
{
int i = 0;
PSD p=pHead;
while(p->next!=NULL)
{
i++;
p=p->next;
}
return i;
}
bool sort_list(PSD pHead)
{
cout<<"由小到大排序..."<<endl;
PSD p=pHead->next,q;
int t;
for(p;p!=NULL;p=p->next)
for(q=p->next;q!=NULL;q=q->next)
if(p->data>q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
traverse_list(pHead);
return true;
}
bool insert_list(PSD pHead)
{
int n,x;
cout<<"请输入在第几个前插入:";
cin>>n;
cout<<"插入数据为:";
cin>>x;
int i=0;
PSD p=pHead;
while(i<n-1)
{
p=p->next;
i++;
}
if(p == NULL)
{
cout<<"插入失败!"<<endl;
exit(-1);
}
PSD pNew = (PSD)malloc(sizeof(SD));
if(pNew == NULL)
{
cout<<"创建失败!"<<endl;
exit(-1);
}
pNew->data = x;
PSD t=p->next;
p->next = pNew;
pNew->next = t;
return true;
}
bool traverse_list(PSD pHead)
{
cout<<"输出:"<<endl;
PSD p=pHead->next;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
return true;
}
bool delete_list(PSD pHead)
{
cout<<"删除第几个节点: ";
int i=0,n;
cin>>n;
if(n>length_list(pHead))
{
cout<<"删除失败!"<<endl;
return false;
}
PSD p = pHead;
while(i<n-1)
{
p = p->next;
i++;
}
PSD j = p->next;
if(n==length_list(pHead))
p->next= NULL;
else
p->next = p->next->next;
delete(j);
j=NULL;
return true;
}