鏈表(線性表)

Problem B: 鏈表(線性表)

 

Description

(線性表)設有一個正整數序列組成的有序單鏈表(按遞增次序有序,且允許有相等的整數存在),試編寫能實現下列功能的算法 :(要求用最少的時間和最小的空間)
(1)確定在序列中比正整數x大的數有幾個(相同的數只計算一次);
(2) 在單鏈表將比正整數x小的數按遞減次序排列;

Input

Sample Output

輸入長度:13

輸入數據:4 5 7 7 8 10 11 15 15 16 17 20 20

輸入x:10

 

Output

5

8 7 7 5 4

Sample Input

7
1 2 3 4 5 6 6
4

Sample Output

2
3 2 1 

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 *p,student *stud)//遞歸輸出
{
	student *p0;
	p0=stud;
	if(p==NULL)
		return ;
	print(p->next,stud);
	if(p0->num>p->num)//只有當p->num比p0->num小時才輸出
	cout<<p->num<<" ";
	
}
student *intset(student *head,student *stud)
{
	int sum=0;
	student *p0,*p1,*p2;
	p1=head;p2=head;
	p0=stud;
	if(head!=NULL)
		do
		{
			if(p0->num<p1->num&&p1->num!=p2->num)
			{	
				sum++;
			}
			p1=p1->next;
			p2=p1->next;
		}while(p2!=NULL);//由p2判斷結束位置
	
	cout<<sum+1<<endl;
	return (head);
}

int main()
{
	int m,num;
	cin>>m;
	student *head,*stud;
	student *creat(int);
	void print(student *,student *);
	student *intset(student *,student *);
	head=creat(m);
	stud=new student;
	cin>>stud->num;
	intset(head,stud);
	print(head,stud);
	return 0;
}





 

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