1,定义节点
typedef struct Node{
int data;
struct Node *next;
};
2,主函数中初始化节点
Node *p=new Node;
3,创建链表(尾插法)
void Create(Node *&p){
int x;
p->next=NULL;
Node *s,*r=p;
cin>>x;
while(x!=-1){
s=new Node;
s->data=x;
r->next=s;
r=s;
cin>>x;
}
r->next=NULL;
}
4,展示链表数据
void Print(Node *&p){
Node *l=p->next;
while(l!=NULL){
cout<<l->data<<" ";
l=l->next;
}
cout<<endl;
}
5,从小到大排序
void Sort(Node *&p){
Node *l=p->next,*pre;
Node *r=l->next;
l->next=NULL;
l=r;
while(l!=NULL){
r=l->next;
pre=p;
while(pre->next!=NULL && pre->next->data<l->data){
pre=pre->next;
}
l->next=pre->next;
pre->next=l;
l=r;
}
}
6,插入链表
void Insert_Node(Node *&p){
Node *l=p->next;
Node *s,*t;
int x;
cin>>x;
s=new Node;
s->data=x;
t=l->next;
l->next=s;
s->next=t;
Sort(p);
Print(p);
}
7,清空链表
void Delete_list(Node *&l){
Node *p=l;
Node *q=p->next;
while(p!=NULL){
delete p;
p=q;
if(q!=NULL){
q=q->next;
}
}
}
8,链表长度
int Length_list(Node *&p){
int sum=0;
if(p==NULL){
return 0;
}
Node *l=p->next;
while(l!=NULL){
sum++;
l=l->next;
}
return sum;
}
完整代码:
#include <iostream>
using namespace std;
//定义节点
typedef struct Node{
int data;
struct Node *next;
};
void Create(Node *&p){
int x;
p->next=NULL;
Node *s,*r=p;
cin>>x;
while(x!=-1){
s=new Node;
s->data=x;
r->next=s;
r=s;
cin>>x;
}
r->next=NULL;
}
void Print(Node *&p){
Node *l=p->next;
while(l!=NULL){
cout<<l->data<<" ";
l=l->next;
}
cout<<endl;
}
//从小到大排序
void Sort(Node *&p){
Node *l=p->next,*pre;
Node *r=l->next;
l->next=NULL;
l=r;
while(l!=NULL){
r=l->next;
pre=p;
while(pre->next!=NULL && pre->next->data<l->data){
pre=pre->next;
}
l->next=pre->next;
pre->next=l;
l=r;
}
}
//插入
void Insert_Node(Node *&p){
Node *l=p->next;
Node *s,*t;
int x;
cin>>x;
s=new Node;
s->data=x;
t=l->next;
l->next=s;
s->next=t;
Sort(p);
Print(p);
}
//清空链表
void Delete_list(Node *&l){
Node *p=l;
Node *q=p->next;
while(p!=NULL){
delete p;
p=q;
if(q!=NULL){
q=q->next;
}
}
}
//链表长度
int Length_list(Node *&p){
int sum=0;
if(p==NULL){
return 0;
}
Node *l=p->next;
while(l!=NULL){
sum++;
l=l->next;
}
return sum;
}
int main()
{
int length;
Node *p=new Node;
cout<<"请输入链表中的数据:"<<endl;
Create(p);
Print(p);
cout<<"链表长度:";
length=Length_list(p);
cout<<length<<endl;
cout<<"从小到大排序:"<<endl;
Sort(p);
Print(p);
cout<<"插入数据:"<<endl;
Insert_Node(p);
cout<<"清空链表"<<endl;
Delete_list(p);
return 0;
}
结果截图: