数据结构之单链表(尾插法)查找、插入和删除

来源:互联网 发布:最新易语言dnf辅助源码 编辑:程序博客网 时间:2024/06/06 14:03

这一次的难度主要体现在长,常常的代码让人望而生畏,不过,只要理解清楚了查找、插入和删除就好办了
代码

#include<stdio.h>#include<malloc.h>typedef struct node{    int data;    struct node*next;}node;node*creat(){    node*head,*q,*p;    char ch;    int a;    head=(node*)malloc(sizeof(node));    q=head;    ch='*';    puts("单链表尾插法,?结束");    while(ch!='?')    {        scanf("%d",&a);        p=(node*)malloc(sizeof(node));        p->data=a;        q->next=p;        q=p;        ch=getchar();    }    q->next=NULL;    return(head);}node*find(node*head,int x){    node*p;    p=head->next;    while((p!=NULL)&&(p->data!=x))    p=p->next;    return p;}void insert(node*p,int x){    node*q;    q=(node*)malloc(sizeof(node));    q->data=x;    q->next=p->next;    p->next=q;}void del(node*head,int x){    node*p,*q;    q=head;    p=q->next;    while((p!=NULL)&&(p->data!=x))    {        q=p;        p=p->next;    }    if(p==NULL)    {        printf("error\n");    }    else{        q->next=p->next;        free(p);    }}int main(){    node*a,*b,*c;    int x,y;    a=creat();    printf("you want to find: ");scanf("%d",&x);    b=a;    b=find(a,x);    if(b!=NULL)        printf("\nfind the value:%d",b->data);    else    {        printf("error");        return -1;        }    printf("\ninput be inserted value: ");scanf("%d",&y);    printf("\ninsert the %d `s next",x);    insert(b,y);    c=a;    printf("\nprint the list\n");    while(a->next!=NULL)    {        a=a->next;        printf("%d ",a->data);     }      printf("\nyou want to del:");scanf("%d",&x);     del(c,x);     c=c->next;     printf("the new list:\n");     while(c!=NULL)     {        printf("%d ",c->data);        c=c->next;     }     return 0;}

总结

这一次感觉还是收获挺大的,主要是意识到指针是真的是个好东西啊,随随便便就可以指向一个地址,好东西。查找、插入和删除对于单链表来说比较简单,就不介绍了,代码也相对简单,就是臃肿了点。

1 0