C/C++语言实现单链表的相关操作(创建,查找等)

#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;
    }
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值