数据结构上机测试2-1:单链表操作A

来源:互联网 发布:vscode 代码提示 编辑:程序博客网 时间:2024/06/06 00:16

题目描述

输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。

输入

第一行输入数据个数n;
第二行依次输入n个整数;
第三行输入欲删除数据m。

输出

第一行输出原始单链表的长度;
第二行依次输出原始单链表的数据;
第三行输出完成删除后的单链表长度;
第四行依次输出完成删除后的单链表数据。

示例输入

1056 25 12 33 66 54 7 12 33 1212

示例输出

1056 25 12 33 66 54 7 12 33 127

56 25 33 66 54 7 33

源代码C下可正常运行

#include<stdio.h>#include<stdlib.h>#include<malloc.h>struct node{    int data;    struct node*next;};struct node*create(int n){    struct node*head,*tail,*p;    int i;    head=(struct node*)malloc(sizeof(struct node));    head->next=NULL;    tail=head;    for(i=0;i<n;i++)    {        p=(struct node*)malloc(sizeof(struct node));        scanf("%d",&p->data);        p->next=NULL;        tail->next=p;        tail=p;    }    return (head);};void Delete(struct node*h,int m){    struct node*p=h;    while(p->next!=NULL)    {        if(p->next->data==m)        {            p->next=p->next->next;        }        else            p=p->next;    }}void print(struct node*h){    struct node*p=h->next;    while(p!=NULL)    {        if(p->next==NULL)            printf("%d\n",p->data);        else            printf("%d ",p->data);        p=p->next;    }}void num(struct node *p){    int i;    i=0;    struct node *h=p->next;    while(h!=NULL)    {        i++;        h=h->next;    }    printf("%d",i);}int main(){    int n,m;    struct node*p;    scanf("%d",&n);    p=create(n);    scanf("%d",&m);    num(p);    printf("\n");    print(p);    Delete(p,m);    num(p);    printf("\n");    print(p);    printf("\n");    return 0;}


0 0
原创粉丝点击