Homework:
给定一条单向链,设计程序把链倒过来,并输出结果。要求直接在这条链上完成倒置操作,只可增设有限的几个辅助变量。

Code
#include <iostream>
#include <string>
using namespace std;
struct Node
{
string content;
Node *next;
};
class Chain
{
private:
Node *pHead;
Node *pTail;
int length;
public:
Chain(){pHead=NULL;pTail=NULL;length=0;}
~Chain(){};
int countNodes();
Node* getHead(){return pHead;}
Node* getTail(){return pTail;}
void insertNode(string);
void reverse(int n,Node *ph); //实现链的倒置
void print();
};
int Chain::countNodes()
{
return length;
}
void Chain::insertNode(string s)
{
Node *p=new Node;
p->content=s;
p->next=NULL;
if(pHead==NULL)
{
pHead=p;
pTail=p;
}
else
{
pTail->next=p;
pTail=p;
}
++length;
}
void Chain::print()
{
Node *p=pHead;
if(pHead==NULL)
cout<<"It is an empty chain!"<<endl;
else
do
{
cout<<p->content<<"->";
p=p->next;
}while(p!=NULL);
cout<<endl;
}
void Chain::reverse(int n,Node *ph)
{
if(n <= 1)
{
Node *ptemp=pHead;
pHead=pTail;
pTail=ptemp;
return;
}
reverse(n-1,ph->next);
ph->next->next=ph;
ph->next=0;
}
int main()
{
Chain chain;
string s="";
int i=1,n=0;
Node *ph;
while(s != "#")
{
cout<<"Input No."<<i<<" node:";
cin>>s;
if(s == "#")
break;
chain.insertNode(s);
++i;
}
chain.print();
n=chain.countNodes();
ph=chain.getHead();
chain.reverse(n,ph);
chain.print();
return 0;
}