求各位大神帮帮萌新解决一下,谢谢,我真的是解决不了了,都煎熬了8个小时了。
#include<string>
using namespace std;
const int MaxSize = 20;
class LinkList
{
private:
struct Node *first;
public:
LinkList();
LinkList(int a[], int n);
void Insert(int n);
int Locate(int n);
int Get(int n);
int Delete(int n);
int Length();
void View();
};
struct Node
{
int data;
Node *next;
};
LinkList::LinkList()
{
first = new Node;
first->next = NULL;
}
LinkList::LinkList(int a[], int len)
{
struct Node *rear;
first = new Node;
first->next = NULL;
rear = first;
for (int i = 0; i < len; i++)
{
rear = new Node;
rear->data = a[i];
first->next = rear;
rear->next = NULL;
}
}
void LinkList::Insert(int n)
{
for (int t = 0; t < n ; t++)
{
int i;
int x;
cin >> i >> x;
Node * rear;
Node * s;
rear = first;
for ( int j=0; rear!=NULL&&j < i-1; j++)
{
rear = rear->next;
}
if (rear==NULL)
{
throw("位置不正确");
}
else
{
s = new Node;
s->data = x;
s->next = rear->next;
rear->next = s;
}
}
}
int LinkList::Get(int n)
{
Node *p = first->next;
int count = 1;
while (p!=NULL && count<n)
{
p = p->next;
count++;
}
if (p==NULL)
{
throw"位置不正确";
}
else
{
return p->data;
}
}
int LinkList::Delete(int i)
{
Node *p;
Node *q;
int x;
p = first;
int count = 0;
while (p!=NULL&&count<i-1)
{
p = p->next;
count++;
}
if (p->next==NULL)
{
throw"位置不正确";
}
else if (first->next==NULL)
{
throw"下溢";
}
else
{
q = p->next;
x = q->data;
p->next = q->next;
delete q;
return x;
}
}
int LinkList::Length()
{
Node *p;
int count = 0;
p = first->next;
while (p!=NULL)
{
p = p->next;
count++;
}
return count;
}
void LinkList::View()
{
Node *p;
p = first->next;
while (p!=NULL)
{
cout << p->data << endl;
p = p->next;
}
}
int LinkList::Locate(int x)
{
Node *p;
p = first->next;
int count = 1;
while (p!=NULL)
{
if (p->data==x)
{
return count;
}
p = p->next;
count++;
}
throw"None";
return 0;
}
int main()
{
LinkList A;
for (int i = 0; i < 8; i++)
{
string x;
cin >> x;
if (x == "I" )
{
int t;
cin >> t;
A.Insert(t);
}
else if (x =="S")
{
int t;
cin >> t;
cout<<A.Locate(t)<<endl;
}
else if (x =="G")
{
int t;
cin >> t;
cout<<A.Get(t)<<endl;
}
else if (x == "D")
{
int t;
cin >> t;
cout << A.Get(t) << endl;
A.Delete(t);
}
else if (x =="L")
{
cout << A.Length() << endl;
}
else if (x =="V")
{
A.View();
}
else if (x =="E")
{
return 0;
}
}
return 0;
}