结构体与链表练习 删除数组中的元素

描述

给定N个整数,将这些整数中与M相等的删除 
假定给出的整数序列为:1,3,3,0,-3,5,6,8,3,10,22,-1,3,5,11,20,100,3,9,3 
应该将其放在一个链表中,链表长度为20 
要删除的数是3,删除以后,链表中只剩14个元素:1 0 -3 5 6 8 10 22 -1 5 11 20 100 9

要求:必须使用链表,不允许使用数组,也不允许不删除元素直接输出 
      程序中必须有链表的相关操作:建立链表,删除元素,输出删除后链表中元素,释放链表 
      不符合要求的程序即使通过,也会算作0分 

输入
输入包含3行:
第一行是一个整数n(1 <= n <= 200000),代表数组中元素的个数。
第二行包含n个整数,代表数组中的n个元素。每个整数之间用空格分隔;每个整数的取值在32位有符号整数范围以内。
第三行是一个整数k,代表待删除元素的值(k的取值也在32位有符号整数范围内)。
输出
输出只有1行:
将数组内所有待删除元素删除以后,输出数组内的剩余元素的值,每个整数之间用空格分隔。
样例输入
20
1 3 3 0 -3 5 6 8 3 10 22 -1 3 5 11 20 100 3 9 3
3
样例输出
1 0 -3 5 6 8 10 22 -1 5 11 20 100 9
#include<stdio.h>
struct stu
{
   int num;
   struct stu *next;
};
void creat(struct stu *head,int i)
{
    struct stu *p;
    head->next=NULL;
    while(i--)
	{
        p=new stu;
        scanf("%d",&p->num);
        p->next=head->next;
        head->next=p;
        head=p;
	}
}

void dele(struct stu *head,int k)
{
    struct stu *p=head;
    head=head->next;

    while(head!=NULL)
	{
        if(head->num==k)
		{
            p->next=head->next;
            head=p->next;

		}
        else
		{
            p=p->next;
            head=head->next;
		}
	}

}
void print(struct stu *head)
{
    head=head->next;
    while(head!=NULL)
	{
        printf("%d ",head->num);
        head=head->next;
	}
    printf("\n");
}
int main()
{
    int n;
    int k;
    stu *head=new stu;
    scanf("%d",&n);
    creat(head,n);
	scanf("%d",&k);
    dele(head,k);
    print(head);
	return 0;
}

另一种方法
<pre name="code" class="cpp">#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct data)
struct data
{
    int num;
    struct data *next;
};
struct data* creat(int n)//创建链表
{
	struct data *p1,*p2,*head;
	int i=0;
	p1=head=NULL;
	while(n--)
	{
	        i++;
	        p1=(struct data*)malloc(LEN);
	        if(i==1)
		head=p1;//如果是第一个结点,使head=p1,让head指向新开辟的结点
                        else
		p2->next=p1;//如果不是,令p2指向前一个结点,新结点地址赋给上一个的next
	        p2=p1;//使p2指向新建立的结点
                        scanf("%d",&p1->num);
	}	
                p2->next=NULL;
                return head;
}
struct data * del(int k,struct data *head)//删除节点
{
	struct data *p1,*p2;
	for(p2=p1=head;p1!=NULL;)
	{
		if(p1->num==k)
		{
			if(p1==head)
			{
				head=p1->next;
				free(p1);//l若p1指向首结点,将第二个结点地址赋给head
			}
			else
			{
				p2->next=p1->next;
				free(p1);//若不是就将下一结点的地址赋给前一结点地址
				p1=p2->next;
			}
		}
		else
		{
			p2=p1;
			p1=p1->next;
		}
	}
	return head;
}
int main()
{
	int n,k;
	struct data *p;
	scanf("%d",&n);
	p=creat(n);
	scanf("%d",&k);
	p=del(k,p);
	if(p!=NULL)
	{
		while(p->next!=NULL)
		{
			printf("%d ",p->num);
			p=p->next;
		}
		printf("%d\n",p->num);
	}
	return 0;
}


 
 
 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值