请设计时间和空间上都尽可能高效的算法,求链式存储的线性表的倒数第m个元素

#include
using namespace std;
typedef struct PolyNode * Polynomial;
struct PolyNode {
	int Data;
	Polynomial link;
};
void Attach(int data, Polynomial * PtrRear)
{
	Polynomial P= new struct PolyNode;
	P->Data = data;
	P->link = NULL;
	(*PtrRear)->link = P;
	(*PtrRear) = P;
}
Polynomial ReadPoly()
{
	Polynomial P, t,Rear;
	P = new struct PolyNode;
	P->link = NULL;
	int N,num;
	cin >> N;
	cin.get();
	cout << endl;
	Rear = P;
	while (N--)
	{
		cin >> num ;
		cin.get();
		Attach(num, &Rear);
	}
	cout << endl;
	t = P;
	P = P->link;
	free(t);
	return P;
}
void Print(Polynomial P)
{
	while (P)
	{
		cout << P->Data<<" ";
		P = P->link;
	}
}
int Find(Polynomial P, int m)
{
	int a[1000];
	int count = 0;
	while (P)
	{
		a[count] = P->Data;
		count++;
		P = P->link;
	}
	if (count < m)return -1;
	else
		return a[count - m];
}
void main()
{
	int m;
	Polynomial P;
	P = ReadPoly();
	cin >> m;
	cout << Find(P, m) << endl;
	Print(P);
	cin.get();
	
}

熟悉ReadPoly的写法,Attach()的写法。

把链表元素存入数组,再找倒数第m个元素。

你可能感兴趣的:(数据结构)