<span style="font-size:18px;">// LinkedList2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
typedef int ElemType;
using namespace std;
struct Node
{
ElemType elem;
Node* pNext;
} Node;
typedef struct Node* PNode;
class LinkedList
{
private:
PNode pHead;
public:
LinkedList(int i)
{
PNode pNew,pTail;
pHead=(PNode)new PNode;
pTail=pHead;
for(int j=0;j<i;j++)
{
pNew=(PNode)new PNode;
pTail->pNext=pNew;
pNew->elem=j+1;
pNew->pNext=NULL;
pTail=pNew;
cout << "pTail=" << pTail << " pHead=" << pHead << endl;
}
}
~LinkedList()
{
PNode p=pHead;
PNode q;
ofstream out_file("text.txt" );
if ( ! out_file )
{ cerr << "oops! unable to open output file\n"; }
while(p->pNext)
{
//cout << p->elem << ' ';
q=p;
p=p->pNext;
cout << "free:" << q << endl;
delete q;
q=NULL;
//free(q);
out_file << "free:" << q << endl;
}
delete p;
p=NULL;
}
void Show()
{
PNode p=pHead->pNext;
while(p!=NULL)
{
cout << p->elem << ' ';
p=p->pNext;
}
cout << endl;
}
PNode GetElem(int i)
{
PNode pn=pHead;
int j=0;
while(pn->pNext && j<i)
{
cout << "pn=" << pn << ' ';
pn=pn->pNext;
j++;
}
cout << "return-pn=" << pn << endl;
return pn;
}
bool Insert(ElemType elem, int i)
{
PNode p=(PNode)new PNode();
PNode q;
p->elem=elem;
q=GetElem(i-1);
p->pNext=q->pNext;
q->pNext=p;
return true;
}
ElemType Delete(int i)
{
PNode p=GetElem(i);
GetElem(i-1)->pNext=p->pNext;
return p->elem;
}
};
int main(void)
{
LinkedList* _ll=new LinkedList(5);
_ll->Show();
//delete _ll;
_ll->Insert(111,4);
_ll->Insert(222,4);
//_ll->GetElem(3);
_ll->Show();
cout << "您删除的元素是:" << _ll->Delete(5) << endl;
_ll->Show();
system("pause");
return 0;
}</span>