c++链表的基本操作建立,插入,删除,输出。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define N sizeof(struct node)
using namespace std;
struct node
{
int num;
node *next;
};
void jianli(node * &head,int &n)//建立链表;
{
n=0;
head=NULL;
node *p1,*p2;
p1=p2=(struct node*)malloc(N);
cin>>p1->num;
while(p1->num!=-1)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct node*)malloc(N);
cin>>p1->num;
}
p2->next=NULL;
}
void charu(node *&head,int &n)//插入操作;
{
node *p1,*p2,*p;
p=(struct node*)malloc(N);
cin>>p->num;
if(head==NULL)//若链表为空;
{
head=p;
p->next=NULL;
}
else//链表不为空;
{
if(p->num<head->num||p->num==head->num)//在头结点前插入;
{
p->next=head;
head=p;
}
else//在表中插入(包括表尾);
{
p2=head;
p1=head->next;
while(p1!=NULL)
{
if(p->num>p1->num)
{
p2=p1;
p1=p1->next;
}
else
break;
}
p2->next=p;
p->next=p1;
}
n=n+1;
}
}
void shanchu(node *&head,int &n)//删除操作;
{
node *p1,*p2,*p;
p=(struct node*)malloc(N);
cin>>p->num;
if(head==NULL)//链表为空;
cout<<"空表!";
else//链表非空;
{
while(p->num==head->num)//删除的节点为头结点或者链表头开始有连续的相同数据;
{
head=head->next;
n=n-1;
if(n==0)
{
cout<<"表中已经没有数据!";
return;
}
}
p2=head;//要删出的结点点不是头结点;
p1=head->next;
while(p1!=NULL)
{
if(p->num!=p1->num)
{
p2=p1;
p1=p1->next;
}
else
{
p2->next=p1->next;
p1=p1->next;
n=n-1;
}
}
if(n==0)//表中的数据被删光;
cout<<"表中已经没有数据!";
}
}
void shuchu(node *&head)
{
node *p;
p=head;
while(p!=NULL)
{
cout<<p->num<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
int n;
node *head;
jianli(head,n);
shuchu(head);
cout<<"请输入需要插入的数据:";
charu(head,n);
shuchu(head);
cout<<"请输入需要删除的数据:";
shanchu(head,n);
shuchu(head);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值