数据结构单链表基本操作

#include <stdio.h>
#include
#include
using namespace std;

typedef struct lnode
{
int data;
struct lnode *next;
}node;

void creatlist1(node *&L,int a[],int n)
{
node *s;
L=(node *)malloc(sizeof(node));
L->next=NULL;
for(int i=0;i<n;i++)
{
s=(node *)malloc(sizeof(node));
s->data=a[i];
s->next=L->next;
L->next=s;
}
}

void creatlist2(node *&L,int a[],int n)
{
node *s,*r;
L=(node *)malloc(sizeof(node));
r=L;
for(int i=0;i<n;i++)
{
s=(node *)malloc(sizeof(node));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}

void dislist(node *&L)
{
node *p=L->next;
while(p!=NULL)
{
printf("%d “,p->data);
p=p->next;
}
printf(”\n");
}

void init(node *&L)
{
L=(node *)malloc(sizeof(node));
L->next=NULL;
}

void destroylist(node *&L)
{
node *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
free(pre);
}

bool listempty(node *&L)
{
return (L->next==NULL);
}

int listlength(node *&L)
{
int n=0;
node *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return n;
}

bool getelem(node *L,int i,int &e)
{
int j=0;
node *p=L;
if(i<=0)
return false;
while(j<=i&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
e=p->data;
return true;
}
}

int locateelem(node *&L,int e)
{
int i=1;
node *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(p==NULL)
return 0;
else
return i;
}

bool listinsert(node *&L,int i,int e)
{
int j=0;
node *p=L,*s;
if(i<=0)
return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
s=(node *)malloc(sizeof(node));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}

bool listelete(node *&L,int i,int &e)
{
int j=0;
node *p=L,*q;
if(i<=0)
return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(pNULL)
return false;
else
{
q=p->next;
if(q
NULL)
return false;
e=q->data;
p->next=q->next;
free(q);
return true;
}
}

int main()
{
int e;
node *L;
init(L);
int n;
int a[1000];
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
creatlist1(L,a,n);
dislist(L);
creatlist2(L,a,n);
dislist(L);

if(listempty(L))
{
    cout<<"NO"<<endl;
}
else
{
    cout<<"YES"<<endl;
}

if(getelem(L,4,e))
{
    cout<<"Yes"<<endl;
}

cout<<listlength(L)<<endl;

cout<<locateelem(L,4)<<endl;

listinsert(L,4,3453);

dislist(L);

listelete(L,4,e);

dislist(L);

destroylist(L);
return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值