#include<iostream>
using namespace std;
//尾插法,头插法
//按序号查找,按值查找,插入结点,求表长
typedef struct node
{
int data; //数据域
struct node *next; //指向下一个节点的指针
} node,*linklist;
linklist CreateList_R(linklist &L){ //尾插法创造链表
cout<<"when createlist L is :"<<L<<endl;
node *s;
int x;
node *r;
L=(linklist)malloc(sizeof(node));
cout<<"after malloc L is :"<<L<<endl;
r=L;
cin>>x;
while(x!=9999){
s=(node*)malloc(sizeof(node));
s->data=x;
r->next=s;
r=s;
cin>>x;
}
r->next=NULL;
return L;
}
linklist CreateList_H(linklist &L) //头插法创造链表
{ node *s;
cout<<s<<endl;
int x;
L=(linklist) malloc(sizeof(node)); //先建立一个带头结点的单链表
L->next=NULL;
cin>>x;
while(x!=9999)
{
s= (node*) malloc(sizeof(node)); //动态开辟新的结点
s->data=x;
s->next=L->next;
L->next=s;
cin>>x;
}
return L;
}
node* search_num(linklist &L,int k){ //按序号查找
cout<<"when search_num L is :"<<L<<endl;
int i=1;
node *q=L->next;
if(k==0)
return L;
if(k<1)
return NULL;
while(q&&i<k){
q=q->next;
i++;
}
return q;
}
node* search_x(linklist &L,int x){ //按值查找
node *q=L->next;
while(q!=NULL&&q->data!=x){
q=q->next;
}
return q;
}
void insertlist(linklist &L,int i,node *s){ //将结点s插入第i个位置上
node *p;
p=search_num(L,i-1);
s->next=p->next;
p->next=s;
}
int getlength(linklist &L){
node *p;int i=0;
p=L;
while(p!=NULL){
i++;
p=p->next;
}
return i-1; //p指空时,i会多加一次要减掉
}
void delete_x(linklist &L,int x){
node *p;
if(L==NULL)
return;
if(L->data==x){
p=L;
L=L->next;
free(p);
delete_x(L,x);
}else
{
delete_x(L->next,x);
}
}
int main(){ //主函数
node *p;
linklist L;
cout<<p<<endl;
cout<<"when createlist L is :"<<L<<endl;
p=CreateList_R(L); //调用尾插法创造链表函数
/* node *n;
n=search_num(p,4); //调用按序号查找函数
cout<<n->next->data<<endl;
*/
delete_x(p,7); //递归删除7
int m=getlength(p);
cout<<"the length of this linklist is "<<m<<endl;
p=p->next; //遍历创造的链表
while (p!=NULL){
cout<<p<<endl;
p=p->next;
}
}
C/C++语言实现单链表的相关操作(创建,查找等)
最新推荐文章于 2024-03-06 16:19:53 发布