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

本文介绍了一个使用C++实现的链表删除指定值节点的程序。该程序首先读取链表的长度和各节点值,然后读取需要删除的节点值,并从链表中删除所有该值的节点。最后,输出修改后的链表。程序通过动态创建链表节点,并遍历链表来查找和删除目标节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 传送门

代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

struct node{
	int data;
	struct node *next;
};

int main()
{
    int n, i, cnt, m;
    struct node *head,  *tail, *p, *q;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    tail = head;
    while(~scanf("%d", &n))
	{
		cnt = 0;
		for(i=0; i<n; i++)
		{
			p = new node;
            p->next = NULL;
            scanf("%d", &p->data);
            tail->next = p;
            tail = p;
		}
		scanf("%d", &m);

		printf("%d\n", n);
		tail = head->next;
		while(tail!=NULL)
		{
			if(tail->next==NULL)
				printf("%d\n", tail->data);
			else printf("%d ", tail->data);
			tail= tail->next;
		}
		p = head;
		q = head->next;
		while(q!=NULL)
		{
			if(q->data==m)
			{
			    p->next = q->next;
			    free(q);
			    cnt++;
			}
			else
				p = p->next;
			q = p->next;
		}
		printf("%d\n", n-cnt);
        tail = head->next;
		while(tail!=NULL)
		{
			if(tail->next==NULL)
				printf("%d\n", tail->data);
			else printf("%d ", tail->data);
			tail = tail->next;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值