单链表的基本运算算法
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<windows.h>
using namespace std;
typedef int elemtype;
typedef struct lnode{
elemtype data;
struct lnode *next;
}linknode;
void initlist(linknode *&L){
L=(linknode *)malloc(sizeof(linknode));
L->next=NULL;
}
void tcreatelistf(linknode *&L,elemtype a[],int n){
linknode *s;
L=(linknode *)malloc(sizeof(linknode));
L->next=NULL;
for(int i=0;i<n;i++){
s=(linknode *)malloc(sizeof(linknode));
s->data=a[i];
s->next=L->next;
L->next=s;
}
}
void wcreatelistf(linknode *&L,elemtype a[],int n){
linknode *s,*r;
L=(linknode *)malloc(sizeof(linknode));
r=L;
for(int i=0;i<n;i++){
s=(linknode *)malloc(sizeof(linknode));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void destorylist(linknode *&L){
linknode *pre=L,*p=L->next;
while(p!=NULL){
free(pre);
pre=p;
p=p->next;
}
free(pre);
}
bool listempty(linknode *L){
return (L->next==NULL);
}
int listlength(linknode *L){
int n=0;
linknode *p=L;
while(p->next!=NULL){
n++;
p=p->next;
}
return n;
}
void dislist(linknode *L){
linknode *p=L->next;
while(p!=NULL){
printf("%c ",p->data);
p=p->next;
}
cout<<endl;
}
bool getelem(linknode *L,int i,elemtype &e){
int j=0;
linknode *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(linknode *L,elemtype e){
int i=1;
linknode *p=L->next;
while(p!=NULL&&p->data!=e){
p=p->next;
i++;
}
if(p->data==NULL)
return 0;
else
return i;
}
bool listinsert(linknode *&L,int i,elemtype e){
int j=0;
linknode *p=L,*s;
if(i<=0)
return false;
while(j<i-1&&p->data!=NULL){
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
s=(linknode *)malloc(sizeof(linknode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
bool listdelete(linknode *&L,int i,elemtype &e){
int j=0;
linknode *p=L,*q;
if(i<=0)
return false;
while(j<i-1&&p!=NULL){
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
q=p->next;
if(q==NULL)
return false;
e=q->data;
p->next=q->next;
free(q);
return true;
}
}
int main(){
elemtype a[10];
linknode *L;
elemtype e;
int i;
cout<<"初始化链表h."<<endl;
initlist(L);
cout<<"依次采用尾插法插入元素a,b,c,d,e"<<endl;
a[0]='a';
for(i=1;i<5;i++)
a[i]=a[i-1]+1;
wcreatelistf(L,a,i);
cout<<"输出单链表h:"<<endl;
dislist(L);
cout<<"输出单链表的长度:"<<listlength(L)<<endl;
cout<<"判断单链表是否为空:"<<endl;
printf("%s\n",listempty(L)?"空":"非空");
cout<<"输出单链表的第三个元素:"<<endl;
getelem(L,3,e);
printf("%c\n",e);
cout<<"输出元素a的位置:"<<locateelem(L,'a')<<endl;
cout<<"在第四个元素的位置上插入元素f"<<endl;
listinsert(L,4,'f');
cout<<"输出单链表h:"<<endl;
dislist(L);
cout<<"删除单链表的第三个元素:"<<endl;
listdelete(L,3,e);
cout<<"输出单链表h:"<<endl;
dislist(L);
cout<<"释放单链表h:"<<endl;
destorylist(L);
}