用C语言编写线性链表的删除,插入,逆置等基本操作

利用链表的插入运算建立线性链表,然后实现链表的查找、插入、删除、计数、输出、排序、逆置等运算(查找、插入、删除、查找、计数、输出、排序、逆置要单独写成函数),并能在屏幕上输出操作前后的结果。(能给出源代码并能运行通过的立即给分)

第1个回答  2010-06-07
这是用C++写的,不知道行不行
#include<iostream.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct node
{
elemtype data;
struct node *next;
}Lnode,*Lklist;
void initLklist(Lklist &h)
{
h->next =NULL;
}
//头插法
/*Lklist crea( )
{
Lklist h,s,p;
elemtype x;
h=(Lklist)malloc(sizeof(Lnode));
h->next =NULL; p=h;
cout<<"创建单链表:";
cin>>x;
while(x!=-1)
{
s=(Lklist)malloc(sizeof(Lnode));
s->data=x;
s->next=h->next;
h->next=s;
cin>>x;
}

return h;
}*/
//尾插法
Lklist crea( )
{
Lklist h,s,p;
elemtype x;
h=(Lklist)malloc(sizeof(Lnode));
h->next =NULL; p=h;
cout<<"创建单链表:";
cin>>x;
while(x!=-1)
{
s=(Lklist)malloc(sizeof(Lnode));
s->data=x;
p->next=s;
p=s;
cin>>x;
}
p->next=NULL;
return h;
}

int lengthLklist(Lklist h)
{
Lklist p;
p=h;int j=0;
while(p->next)
{
p=p->next;
j++;
}
return j;
}
Lklist getLklist(Lklist h,int i)
{
Lklist p;
p=h;int j=0;
while(p->next &&j<i)
{
p=p->next ;
j++;
}
if(j==i) return p;
else return NULL;
}
void insertLklist(Lklist h,int i,elemtype x)
{
Lklist p;
Lklist s;
s=(Lklist)malloc(sizeof(Lnode));
s->data =x;
p=getLklist(h,i-1);
s->next =p->next ;
p->next =s;
}
void deleteLklist(Lklist &h,int i/*elemtype x */)
{
Lklist q;Lklist p;
p=h;int j=0;
while(p->next &&j<i-1)
{
p=p->next ;
++j;
}
if(!(p->next ))
{
cout<<"删除位置不合理!";
return;
}
q=p->next ;
p->next=q->next;
/*x=q->data;*/
free(q);
}
void transLklist(Lklist &h)
{
Lklist p,q;
p=h->next;
h->next=NULL;
while(p)
{
q=p;
p=p->next;
q->next=h->next;
h->next=q;
}
}
void mergeLklist(Lklist &La,Lklist &Lb,Lklist &Lc)
{
Lklist pa,pb,pc;
pa=La->next ;
pb=Lb->next ;
Lc=pc=La;
while(pa&&pb)
{
if(pa->data<=pb->data)
{
pc->next=pa;
pc=pa;
pa=pa->next;
}
else
{
pc->next=pb;
pc=pb;
pb=pb->next;
}
}
pc->next=pa?pa:pb;
free(Lb);
}
void print(Lklist h)
{
Lklist p;
p=h->next;
while(p)
{
cout<<p->data <<" ";
p=p->next ;
}
}
void main()
{
Lklist h,p,q;
int i,x;
h=crea( );
p=crea( );
q=(Lklist)malloc(sizeof(Lnode));
cout<<"原单链表1:";
print(h);
cout<<endl<<"原单链表2:";
print(p);
cout<<endl<<"单链表1长为:"<<lengthLklist(h);
cout<<endl<<"输入要查找的元素位置i:";
cin>>i;
h=getLklist(h,i);
cout<<"查找后的单链表1:";
print(h);
cout<<endl<<"输入要插入的位置i和插入元素x:";
cin>>i>>x;
insertLklist(h,i,x);
cout<<"插入后的链表1:";
print(h);
cout<<endl<<"要删除的元素位置i:";
cin>>i;
deleteLklist(h,i);
cout<<"删除后的链表1:";
print(h);
cout<<endl<<"合并后的有序表:";
mergeLklist(h,p,q);
print(h);
transLklist(h);
cout<<endl<<"就地转置后的链表:";
print(h);
}