游客 Signup | Login
中文 | En

3584 - 线性链表的删除

输入一个正整数序列,遇负数时停止,建立一个线性链表存储读入的数据,然后从键盘读入一数据x,在该链表中删除比x大的数据后输出。

Input

Output

Examples

Input

1 2 3 4 5 -1
3

Output

1 2 3

Solution C

#include<stdio.h>
#include<stdlib.h>

typedef struct tagNODE
{
	int data;
	struct tagNODE *next;
}node,*linklist;

void linkcreat(linklist *head)
{
	linklist temp,upd;
	int buffer;
	(*head)=(linklist)malloc(sizeof(node));
	(*head)->next=NULL;
	upd=(*head);
	scanf("%d",&buffer);
	while(buffer>0)
	{
		temp=(linklist)malloc(sizeof(node));
		temp->next=NULL;
		upd->next=temp;
		temp->data=buffer;
		upd=temp;
		scanf("%d",&buffer);
	}
}
void linkdelet(linklist head,int x)
{
	linklist temp,val;
	temp=head;
	while(temp->next!=NULL)
	{
		if(temp->next->data>x)
		{
			val=temp->next;
			temp->next=temp->next->next;
			free(val);
			val=NULL;
			continue;
		}
		if(temp->next!=NULL)
			temp=temp->next;
	}
}

void linkput(linklist head)
{
	linklist temp;
	temp=head;
	while(temp->next!=NULL)
	{
		temp=temp->next;
		printf("%d ",temp->data);
	}
}
int main()
{
	int x;
	linklist temp,head;
	linkcreat(&head);
	scanf("%d",&x);
	linkdelet(head,x);
	linkput(head);
	return 0;
}

Solution C++

#include<bits/stdc++.h>
using namespace std;
struct node{
	int data;
	node *next;
};

void Print(node *h){
	node *x = h->next;
	while(x!=NULL){
		cout<<x->data<<" ";
		x = x->next; 
	} 
} 

void Delete(node *h,int val){
	node *x = h,*y;
	while(x!=NULL){
		if(x->next!=NULL&&x->next->data>val){
			y = x->next;
			x->next = y->next;
			delete y;
		} 
		else{
			x = x->next;
		}
	} 
}
int main()
{
	node *h,*p,*r;
	h = new node;
	h->next = NULL; 
	r = h; 
	int x;
	while(cin>>x&&x!=-1){
		p = new node;
		p->data = x;
		p->next = NULL; 
		r->next = p;
		r = p;
	}
	cin>>x;
	Delete(h,x);
	Print(h);
	return 0;
}

Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题