Description
已知长度为n的线性表A采用顺序存储结构,请写一时间复杂度为0(n)、空间复杂度为0(1)的算法,该算法删除线性表中所有值为item的数据元素。(O(1)表示算法的辅助空间为常量)。
Input
输入 n:6
输入数据:1 2 3 4 5 6
输入 item:5
Output
输出:1 2 3 4 6
Sample Input
10
1 2 3 4 5 6 7 8 9 10
8
Sample Output
1 2 3 4 5 6 7 9 10
#include <iostream>
using namespace std;
struct number
{
int num;
number *next;
};
number *creatlink(number *head,int n);
number *sort(number *head,int n);
int main()
{
int n,m;
number *head,*p;
head=NULL;
cin>>n;
head=creatlink(head,n);
cin>>m;
head=sort(head,m);
p=head;
while(p!=NULL)
{cout<<p->num<<' ';p=p->next;}
return 0;
}
number *creatlink(number *head,int n)
{ int i;
number *p,*s;
p=head;
for(i=0;i<n;i++)
{ s=new number;
cin>>s->num;
if(head==NULL)
head=s;
else
p->next=s;
p=s;
}
p->next=NULL;
return (head);
}
number *sort(number *head,int n)
{
number *p,*q;
p=head;
if(head==NULL)
return (head);
else
{while(n!=p->num&&p->next!=NULL)
{
q=p;
p=p->next;
}
if(p->num==n&&p->next==NULL)
q->next=NULL;
else if(n==p->num)
{
if(head==p)
head=p->next;
else
q->next=p->next;
}
}
return(head);
}