Description
Input
輸入 n:6
輸入數據:1 2 3 4 5 6
輸入 item:5
Output
輸出:1 2 3 4 6
Sample Input
Sample Output
HINT
#include <iostream>
using namespace std;
struct list //構造
{
int num;
struct list *next;
};
int main()
{
int item;
list *head;
list *creat(void);
void print(list *);
list *del(list *,int);
head=creat();
cin>>item;
head=del(head,item);
print(head);
return 0;
}
list *creat(void)
{
list *head,*p1,*p2;
int i,n;
cin>>n;
head=NULL;
for(i=0;i<n;i++) //輸入鏈表
{ p1=new list;
cin>>p1->num;
if(head==NULL) //頭部輸入時
head=p1;
else
{
p2->next=p1;
}
p2=p1;
}
p2->next=NULL; //最後一個節點的後一個爲NULL
return head;
}
list *del(list *head,int item)
{
list *p1,*p2;
p2=p1=head;
if(item==head->num) //如果爲頭結點
{
head=head->next;
delete p1;
}
else //不是頭結點
{
p2=p1; //p2記錄p1前一個節點的位置
p1=p1->next;
for(;p1!=NULL;p1=p1->next)
{
if(item==p1->num) //找到了
{
p2->next=p1->next; //刪除節點
delete p1;
break;
}
else //沒找到
p2=p1; 向後移動
}
}
return head;
}
void print(list *head)
{
list *p1;
p1=head;
if(head!=NULL)
do
{
cout<<p1->num<<" ";
p1=p1->next;
}while(p1!=NULL);
}