刪除線性表節點(線性表)

Problem D: 刪除線性表節點(線性表)

 

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 

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;
}




 

發佈了58 篇原創文章 · 獲贊 30 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章