数据结构之链表的基本操作

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
    int data;
    struct LNode* next;
}LNode,*LinkList;

LinkList CreatList(int r[]){//建表
    
    int i;
     LNode* head;
     LNode *pre,*p;
    head=(LinkList)malloc(sizeof(LNode));
    head->next=NULL;//创建头结点
    pre=head;

    for(i=0;i<5;i++){
        p=(LinkList)malloc(sizeof(LNode));
        p->data=r[i];
        p->next=NULL;
        pre->next=p;
        pre=p;
    }
    return head;
}

int search(LNode *head,int x){//查找x在head中的个数
    LNode *L;
    int count=0;
    L=head;
    while(L!=NULL){
        if(L->data==x)count++;
        L=L->next;
    }
    return count;

}

LinkList insert(LNode *head,int pos,int x){//将x插入到head为头结点的链表的第pos个位置里
    LNode * L,*p;
    int i;
    L=head;
    for(i=0;i<pos-1;i++){
        L=L->next;
    }
    p=(LNode *)malloc(sizeof(LNode));
    p->data=x;
    p->next=L->next;
    L->next=p;

    return head;
}

LinkList del(LinkList head,int x){//删除链表中值为x的所有结点!!!!!!!!
    LNode * pre,*p;
    pre=head;
    p=head->next;
    while(p){
        if(p->data==x){
            pre->next=p->next;
            free(p);
            p=pre->next;
        }
        else {pre=p;p=p->next;}
    }
    return head;
}

void main(){
    int r[5];
    int i,a,b,c,countt;
    LNode * L,*M,*F,*G;

    printf("请输入:");
    for(i=0;i<5;i++){
        scanf("%d",&r[i]);
    }
    L=CreatList(r);
    M=CreatList(r);
    L=L->next;
    while(L!=NULL){
        
        printf("%d  ",L->data);
        L=L->next;
    }
    /*printf("\n");
    printf("请输入要查找的元素:");
    scanf("%d",&a);
    countt=search(M,a);
    printf("%d",countt);*/

    /*printf("\n");
    printf("请输入要插入的位置:");
    scanf("%d",&b);
    F=insert(M,b,10);
    F=F->next;
    while(F!=NULL){
        printf("%d  ",F->data);
        F=F->next;
    }*/

    printf("\n");
    printf("请输入要删除的元素:");
    scanf("%d",&c);
    G=del(M,c);
    G=G->next;
    while(G!=NULL){
        printf("%d  ",G->data);
        G=G->next;
    }
        
    
}

猜你喜欢

转载自blog.csdn.net/qq_39063044/article/details/88372846