链表的创建,插入,输出操作

#include<iostream>
#include<iomanip>
using namespace std;
struct Node 
{
int n;
Node *next;
};
Node *createList()
{
Node *head,*p; 
char ch;
head=NULL;
cout<<"是否创建链表?(Y/N)"<<endl;
cin>>ch;
while(ch=='Y')
{
p=new Node;
cout<<"请输入节点的值:";
cin>>p->n;
    p->next=head;
head=p;
cout<<"是否继续创建节点?(Y/N)"<<endl;
cin>>ch;
if(ch=='N')
break;
}
return head;
}
void DisplayList(Node *head)
{
int flag=0;
Node *p;
p=head;
while(p!=NULL)
{
flag=1;
cout<<p->n<<setw(4);
p=p->next;}
cout<<endl;
if(flag==0)
cout<<"空链表!"<<endl;
}
Node *insertList(Node *head)//插入函数
{
Node *q,*p;
int flag;
p=new Node;
cout<<"请输入插入的值:";
cin>>p->n;
cout<<endl;
q=head;
if(q==NULL)//判断链表是否为空链表
{p->next=head;
head=p;}
if(q!=NULL)
{
     while(q->n<p->n)//插入在链表中第一个大于插入值的后面
{q=q->next;
if(q->next!=NULL)
flag=1;
else 
{flag=0;break;}
}
if(flag==1)//链表中存在比插入值大的节点
{p->next=q->next;//插入操作
q->next=p;}//插入操作
if(flag==0)//链表中不存在比插入结点大的点,将p作为头节点插入
{ p->next=head;
  head=p;}
}
return head;//返回head头结点,因为插入之后头结点的位置改变了
}
int main()
{
Node *P;
P=createList();
DisplayList(P);
P=insertList(P);
DisplayList(P);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值