单链表—全部操作
初始化、头插、尾插、求长度、遍历、插入、删除、按值查找、按位查找
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct lnode{
int data;
struct lnode *next;
}lnode,*linklist;
bool initlist(linklist &l) //初始化
{
l=(lnode *)malloc(sizeof(lnode));
if(l==NULL)
return 0;
l->next=NULL;
return 1;
}
linklist list_tailinsert(linklist &l) //尾插
{
int x;
lnode *p;
lnode *s;
p=l=(lnode*)malloc(sizeof(lnode));
//l->next=NULL;
cin>>x;
while(x!=0)
{
s=(lnode *)malloc(sizeof(lnode));
s->data=x;
s->next=NULL;
p->next=s;
p=s;
cin>>x;
}
return l;
}
linklist list_headinsert(linklist &l) //头插
{
int x;
lnode *s;
l=(lnode *)malloc(sizeof(lnode));
l->next=NULL;
cin>>x;
while(x!=0)
{
s=(lnode *)malloc(sizeof(lnode));
s->data=x;
s->next=l->next;
l->next=s;
cin>>x;
}
return l;
}
int getlistlength(linklist l) //求长度+遍历
{
int j=0;
lnode *p;
p=l->next;
while(p!=NULL)
{
cout<<"number "<<j<<" is "<<p->data<<endl;
j++;
p=p->next;
}
return j;
}
bool listinsert(linklist &l,int i,int e) //插入
{
lnode *p,*s;
int j=0;
p=l;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL||j>i-1)
{
cout<<"error"<<endl;
return 0;
}
s=(lnode *)malloc(sizeof(lnode));
s->data=e;
s->next=p->next;
p->next=s;
return 1;
}
bool listdelete(linklist &l,int i) //删除
{
lnode *p,*q;
int j=0;
p=l;
while(p->next!=NULL&&j<i-1)
{
j++;
p=p->next;
}
if(p==NULL||j>i-1)
{
cout<<"delete error"<<endl;
return 0;
}
else{
q=p->next;
p->next=q->next;
//e=q->data;
cout<<"delete element is "<<q->data<<endl;
free(q);
return 1;
}
}
int getelem(linklist l,int i) //按位查找
{
lnode *p;
p=l;
int j=0;
while(p->next!=NULL&&j<i)
{
p=p->next;
j++;
}
if(j==i)
return p->data;
else return -1;
}
lnode * locatelem(linklist l,int x) //按值查找
{
lnode *p;
p=l->next;
while(p!=NULL&&p->data!=x)
{
p=p->next;
}
if(p->data==x)
return p;
else return NULL;
}
int main() {
linklist l1;
if(initlist(l1))
cout<<"initlist l1"<<endl;
cout<<getlistlength(l1)<<endl;
list_headinsert(l1);
cout<<getlistlength(l1)<<endl;
cout<<getelem(l1,1)<<" "<<getelem(l1,2)<<" "<<getelem(l1,3)<<" "<<getelem(l1,4)<<endl;
if(listinsert(l1,2,66))
cout<<"insert succeed"<<endl;
getlistlength(l1);
if(listdelete(l1,3))
cout<<"deletex succeed"<<endl;
getlistlength(l1);
//cout<<locatelem(l1,2)<<endl;
//cout<<locatelem(l1,3)<<endl;
cout<<"-----------"<<endl;
linklist l2;
if(initlist(l2))
cout<<"initlist l2"<<endl;
cout<<getlistlength(l2)<<endl;
list_tailinsert(l2);
cout<<getlistlength(l2)<<endl;
cout<<getelem(l2,1)<<" "<<getelem(l2,2)<<" "<<getelem(l2,3)<<" "<<getelem(l2,4)<<endl;
cout << "over\n";
return 0;
}
作者:Cool baby
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.