Using namespace STD.
Struct Node
{
int data;
Node * next;
};
The class LinkList
{
Public:
LinkList ();
LinkList (int a [], int n);
~ LinkList ();
Void PrintList ();
Void Insert (int I, int x);
Private:
Node * first;
};
LinkList: : LinkList ()
{
The first=new Node;
First - & gt; Next=NULL;
}
LinkList: : LinkList (int a [], int n)
{
The first=new Node;
First - & gt; Next=NULL;
for(int i=0; I
Node * s=new Node;
S - & gt; data=https://bbs.csdn.net/topics/a [I];
S - & gt; Next=first - & gt; Next;
First - & gt; Next=s;
}
}
LinkList: : ~ LinkList ()
{
The Node * p=first - & gt; Next;
while(p!=NULL)
{
Node * q=p;
P=p - & gt; Next;
The delete q;
}
Delete the first;
}
Void LinkList: : PrintList ()
{
Node * p;
P=first - & gt; Next;
while(p!=NULL)//I know here instead of NULL to first, but in addition to this, p can change it to?
{
CoutP=p - & gt; Next;
}
Cout
Void LinkList: : Insert (int I, int x)
{
Node * p;
Int j;
P=first; J=0;//pointer initialization p
While (p!=NULL & amp; & J{
P=p - & gt; Next;//work pointer p (one-way
J++;
}
If (p==NULL) throw "location";
The else {
Node * s;
S=new Node;
S - & gt; data=https://bbs.csdn.net/topics/x;//apply for a node s to memory, the data fields for x
S - & gt; Next=p - & gt; Next;//insert node s to node p
P - & gt; Next=s;
}
}
Void main ()
{
Int a []={1, 2, 3, 4, 5};
LinkList test (a, 5);
Test. PrintList ();
Try
{
Test. The Insert (2, 6);
}
The catch (char * s)
{
Cout
Test. PrintList ();
getchar();
}
CodePudding user response:
Insert function, need a pointer to nodes in front of the p, p initialized first - next, with p, with another implementation into,