Problem D: 刪除線性表節點(線性表)
Description
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
HINT
#include <iostream>
#define NULL 0
using namespace std;
struct student//定義結構體
{
int num;
student *next;
};
int n;
student *creat(int m)
{
student *head,*p1,*p2;
p1=p2=new student;
cin>>p1->num;
head=NULL;
n=0;
while(p1->num!=NULL)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=new student;
if(n==m)
{break;}
else
cin>>p1->num;
}
p2->next=NULL;
return(head);
}
void print(student *head)//鏈表的正常輸出
{
student *p;
p=head;
if(head!=NULL)
do
{
cout<<p->num<<" ";
p=p->next;
}while(p!=NULL);//直至p指向空地址時,輸出結束
}
student *del(student *head,int num)//定義函數
{
student *p1,*p2;
p1=head;
while(num!=p1->num&&p1->next!=NULL)//不是我們所要找的數值時
{
p2=p1;
p1=p1->next;//p1指向下一節點
}
if(num==p1->num)//當找到要刪除的num時
{
if(p1==head)//要刪除的數值爲第一個數時
head=p1->next;
else p2->next=p1->next;//否則的話,將下一結點地址賦給前一結點(即跳過num,指向下一個數值)
}
return (head);
}
int main()
{
int m,num;
cin>>m;
student *head;
student *creat(int);
void print(student *);
student *del(student *,int);
head=creat(m);
cin>>num;
del(head, num);
print(head);
return 0;
}