7-2 单向链表1 (10 分)

链表节点定义为: struct Node{ int data; struct Node *next; }

编程实现:输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算: 输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的奇数值结点删除后输出

输入输出示例:括号内为说明

输入样例:

2 (repeat=2)
1 2 3 4 5 6 7 -1
1 3 5 -1

输出样例:

2 4 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node{
	int data;
	struct Node *next;
};
struct Node *Creat_();
struct Node *shanchu(struct Node *head);
void print(struct Node *head);
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		struct Node *head;
		head=NULL;
		head=Creat_();
		head=shanchu(head);
		print(head);
	}
	return 0;	
}
struct Node *Creat_()
{
	int data;
	struct Node *head,*p,*t;
	head=NULL;
	scanf("%d",&data);
	while(data!=-1)
	{
		p=(struct Node *)malloc(sizeof(struct Node));
		p->data =data;
		if(head==NULL)
		{head=p;
			t=head;
		}
		else
		{
			t->next = p;
			t=t->next;
		}
		scanf("%d",&data);
	}
	t->next =NULL;
	return head;
}
struct Node *shanchu(struct Node *head)
{
	struct Node *p,*p1;
	while(head!=NULL&&head->data%2==1)
	{
		p=head;
		head=head->next;
		free(p);
	}
    if(head==NULL)
        return NULL;
	p=head;
	p1=head->next;
	while(p1!=NULL)
	{
		if(p1->data%2==1)
		{
			p->next = p1->next ;
			free(p1);
		}
		else
			p=p->next ;
		p1=p->next ;
	}
	return head;
}
void print(struct Node *head)
{
	struct Node *p;
	for(p=head;p!=NULL;p=p->next)
    {
        if(p->next!=NULL)
        printf("%d ",p->data );
        else
            printf("%d\n",p->data);
    }
    
}

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值