求大神帮忙看看 关于链表的
#include<iostream>#include <stdio.h>
#include<iomanip>
using namespace std;
class ChainNode
{
friend class Chain;
private:
int data;
ChainNode* link;
};
class Chain
{
public:
Chain(){first = 0;}
~Chain();
bool IsEmpty() const {return first == 0;}
int Length() const;
bool Find(int k, int& x);
int Search(const int& x) const;
Chain& Change(int k, int x);
Chain& Delete(int k, int& x);
Chain& Insert(int k, const int& x);
void OutputOne(const ChainNode* current);
void Output();
private:
ChainNode* first;
};
Chain::~Chain()
{
ChainNode * next;
while(first)
{
next = first->link;
delete first;
first = next;
}
}
int Chain::Length() const
{
ChainNode* current = first;
int len = 0;
while(current)
{
len++;
current = current->link;
}
return len;
}
bool Chain::Find(int k,int& x)
{
ChainNode* current = first;
int index = 0;
while(index < k && current )
{
current = current->link;
index++;
}
if(current)
{
x = current->data;
return true;
}
return false;
}
int Chain::Search(const int& x) const
{
ChainNode* current = first;
int index = 1;
while(current && current->data != x)
{
current = current->link;
index++;
}
if(current)
return index;
return 0;
}
/*改为递归,才能先输出高位后输出低位*/
void Chain::OutputOne(const ChainNode* current)
{
if (current)
{
OutputOne(current->link);
if (current->link)
cout<<setw(3)<<current->data;
else
cout<<current->data;/*输出最高位时不能用%03d*/
}
}
void Chain::Output()
{
OutputOne(this->first);
cout<<endl;
}
Chain& Chain::Change(int k, int x)
{
ChainNode* p = first;
for(int index = 0; index < k && p; index++)
p = p->link;
if(p)
p->data = x;
return *this;
}
Chain& Chain::Delete(int k, int& x)
{
ChainNode* p = first;
if(k == 0)
first = first->link;
else
{
ChainNode* q = first;
for(int index = 0; index < k-1 && q; index++)
q = q->link;
p = q->link;
q->link = p->link;
}
x = p->data;
delete p;
return *this;
}
Chain& Chain::Insert(int k, const int& x)
{
ChainNode* p = first;
for(int index = 0; index < k-1 && p; index++) //for(int index = 0; index < k && p; index++)
p = p->link;
ChainNode* y=new ChainNode;
y->data = x;
if(k)
{
y->link = p->link;
p->link = y;
}
else
{
first = y;
y->link = 0;
}
return *this;
}
int main(int argc, char* argv[])
{
Chain c;
int n,i,j,k,l(0);
c.Insert(0,1); //c.Insert(0,2);
cout<<"请输入一个数:";
cin>>n;
for(i = 1; i <= n; i++)
{
int j_end = c.Length();
/*先做乘法*/
for(j = 0; j < j_end;j++)
{
c.Find(j,k);
k = i * k;
c.Change(j,k);
}
/*然后处理进位*/
for(j = 0; j < j_end;j++)
{
c.Find(j,k);
if(k >= 1000)
{
if (j < j_end -1)
c.Find(j+1,l);
else
{
c.Insert(j+1, 0); /*增加高位*/
l = 0;
}
l += k/1000;
c.Change(j+1,l);
k = k % 1000;
c.Change(j,k);
}
}
}
c.Output();
return 0;
}