单链表的顺序建立与结点的删除(期末题复现)

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

函数接口定义:

复制代码
struct node* create(int n);

顺序建立一个带头结点的单链表。其中,n 为读入数据的数目。函数须返回单链表的头节点。

复制代码
void delete(struct node *h,int x);

从单链表删除结点。其中,h 为单链表的头节点,x为删除结点的值。函数不需返回。

复制代码
void print(struct node* h);

输出链表。其中,h 为单链表的头节点。函数不需返回。

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:

复制代码
#include<stdio.h>

#include<stdlib.h>



struct node{

int data;

struct node *next;

};

int n,m;



struct node* create(int n);

void delete(struct node *h,int x);

void print(struct node* h);



int main(){

struct node *h;

scanf("%d",&n);

h=create(n);

scanf("%d",&m);

printf("%d\n",n);

print(h);

delete(h,m);

printf("%d\n",n);

print(h);

return 0;

}

/* 请在这里填写答案 */

输入样例:

在这里给出一组输入。

第一行是输入数据的数目;

第二行是建立链表的输入数据;

第三行是删除结点的值。

例如:

复制代码
10

56 25 12 33 66 54 7 12 33 12

12

输出样例:

在这里给出相应的输出。

第一行输出建立链表后的链表长度;

第二行输出初始单链表;

第三行输出完成删除后的链表长度;

第四行输出完成删除后的单链表;

例如:

复制代码
10

56 25 12 33 66 54 7 12 33 12

7

56 25 33 66 54 7 33

答案:

复制代码
struct node* create(int n){
    struct node *head,*tail,*p;
    head=(struct node *)malloc(sizeof(struct node));
    head->next =NULL;
    tail =head;
    for(int i=0;i<n;i++){
        int x;
        scanf("%d",&x);
        p=(struct  node*)malloc(sizeof(struct node));
        p->data=x;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    return head;
}
void delete(struct node *h,int x){
    struct node *head,*tail,*p;
    head=h;
    p=head->next;
    tail=head;
    while(p!=NULL){
        if(p->data==x){
            tail->next=p->next;
            free(p);
            p=tail->next;
            n--;
        }
        else{
            tail=p;
            p=p->next;
        }
    }
}
void print(struct node* h){
    static int count = 0;  // 静态变量,记录调用次数
    count++;
    struct node *head,*tail,*p;
    head=h;
    p=head->next;
    while(p!=NULL){
        printf("%d",p->data);
        if(p->next!=NULL){
            printf(" ");
        }
        p=p->next;
    }
    if(count==1){
        printf("\n");
    }
    
}
相关推荐
CSharp精选营4 天前
关系型 vs 非关系型:从原理到选型,一文搞定数据库核心分类
数据结构·nosql·关系型数据库·非关系型数据库·技术选型
刘马想放假7 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
北域码匠8 天前
冒泡排序太慢?鸡尾酒排序双向优化,原生 C# 零第三方库完整代码
数据结构·排序算法·泛型·c# 算法·鸡尾酒排序·原生 c# 开发·冒泡排序优化·嵌入式算法
Darling噜啦啦15 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
小小工匠16 天前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
玖玥拾16 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
Qres82116 天前
算法复键——树状数组
数据结构·算法
牛油果子哥q16 天前
并查集(DSU)超精讲,路径压缩、按秩合并、万能模板、连通性判定、最小生成树与刷题实战全解
数据结构·c++·最小生成树·并查集
凌波粒16 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
WL学习笔记16 天前
单项不带头不循环链表
数据结构·链表