链表的创建,遍历以及删除

来源:互联网 发布:送礼物的淘宝店铺 编辑:程序博客网 时间:2024/05/29 05:57

链表的创建,遍历以及删除

博主最近才刚刚开始接触c语言,目前刚刚学到了链表的一些基本使用,比如说创建,遍历和删除链表
先贴段代码

#include <stdio.h>#include <stdlib.h>struct node{    int a;    struct node *next;};int main(){    //创建链表    struct node *head,*q,*p;    head = (struct node*)malloc(sizeof(struct node));    head->next=NULL;    q=head;    int n;    printf("请输入链表长度:");    scanf("%d",&n);    while(n--)    {        p=(struct node*)malloc(sizeof(struct node));        scanf("%d",&p->a);        q->next=p;        p->next=NULL;        q=p;    }    //遍历输出链表    printf("输出链表内容:");    struct node*t=head->next;    while(t!=NULL)    {        printf("%d ",t->a);        t=t->next;    }    printf("\n");    //查找并删除某个节点    int key;    struct node *pre;    pre=head;    printf("输出要查找删除的值:");    scanf("%d",&key);    t=head->next;    while(t!=NULL)    {        if(t->a==key)        {            pre->next=t->next;            break;        }        t=t->next;        pre=pre->next;    }    //输出删除数据后的链表内容    printf("输出删除数据后的链表:");    t=head->next;    while(t!=NULL)     printf("%d ",t->a);     t=t->next;         printf("\n");     return 0;}

其中删除节点还有一个方法可以实现

        if(t->a==key)        {           pre->next=pre->next->next;          break;     }       t=t->next;       pre=pre->next;
阅读全文
0 0
原创粉丝点击