时间限制:1000MS 代码长度限制:10KB
题型: 编程题 语言: G++;GCC
Description
已知长度为n的线性表采用顺序存储结构。写一算法,删除线性表中所有值小于x的元素。
输入格式
第一行 输入表长
第二行 输入指定表长的整数
第三行 输入一个整数
输出格式
第一行 表中的数据
第二行 处理后的表中的数据
输入样例
8
5 3 4 9 8 7 6 2
5
输出样例
5 3 4 9 8 7 6 2
5 9 8 7 6
单链表法:
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
void CreateList(LinkList &L,int n)//创建链表
{
L=new LNode;
LinkList p,r=L;
L->next=NULL;
for(int i=0;i<n;i++)
{
p=new LNode;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
void del(LinkList &L,int x)
{
LinkList p,s;
p=L;
while(p->next)
{
if(p->next->data<x)//找到比p->next->data小的节点,取被删节点的地址信息
{
s=p->next;//临时保存被删节点的地址以备释放
p->next=s->next;
delete s;//删除节点空间
}
else p=p->next;
}
}
int main()
{
int n,x;
cin>>n;
LinkList L,p;
CreateList(L,n);
p=L->next;
while(p)
{
if(p->next) cout<<p->data<<" ";
else cout<<p->data<<endl;
p=p->next;
}
cin>>x;
del(L,x);
p=L->next;
while(p)
{
if(p->next) cout<<p->data<<" ";
else cout<<p->data<<endl;
p=p->next;
}
return 0;
}
简单数组操作(模拟删除):
#include<iostream>
using namespace std;
int a[10005];
int main()
{
int n,x;
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++)
{
if(i==n-1) cout<<a[i]<<endl;
else cout<<a[i]<<" ";
}
cin>>x;
for(int i=0;i<n;i++)
{
if(a[i]<x) continue;
else
{
if(i==n-1) cout<<a[i]<<endl;
else cout<<a[i]<<" ";
}
}
return 0;
}