#include
#include "sub5.hpp"
using namespace std;
struct Node{
int data;
Node* next;
Node(const int& d=int()):data(d),next(NULL){}
};
class Chain
{
private:
Node* head;
int length;
public:
Chain():head(NULL),length(0){}
void delAll()
{
Node* pdel;
while(NULL!=head)
{
pdel=head;
head=head->next;
delete pdel;
}
length=0;
}
~Chain()
{
delAll();
}
Node*& getPoint(int pos)
{
if(pos<0||pos>length)
pos=length;
if(0==pos)
return head;
Node* head_bak=head;
for(int i=1;i
{
head_bak=head_bak->next;
}
return head_bak->next;
}
void insert(const int& data,int pos)
{
Node* pin = new Node(data);
pin->next=getPoint(pos);
getPoint(pos)=pin;
length++;
}
int del(const int& data)
{
int pos=find(data);
if(pos!=-1)
{
Node* &pnext = getPoint(pos);
Node* pbak = pnext;
pnext=pnext->next;
delete pbak;
length--;
}
return pos;
}
int find(const int& data)
{
Node* head_bak=head;
for(int pos=0;head_bak!=NULL;pos++)
{
if(head_bak->data==data)
return pos;
head_bak=head_bak->next;
}
return -1;
}
int editor(const int& oldd,const int& newd)
{
int pos=find(oldd);
if(pos!=1)
{
Node* pedit=getPoint(pos);
pedit->data=newd;
}
return pos;
}
friend ostream& operator<<(ostream& os,const Chain& oc)
{
Node * phead = oc.head;
os<<"[";
while(phead!=NULL)
{
phead=phead->next;
}
os<<"]";
return os;
}
//利用一个辅助指针,存储遍历过程中当前指针指向的下一个元素,
//然后将当前节点元素的指针反转后,利用已经存储的指针往后面继续遍历。
void reverse()
{
Node * pre=head;
Node * cur=head->next;
Node * tmp=NULL;
while(cur)
{
cout<<"in while:"<
data< tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
head->next=NULL;
head=pre;
}
};
void show()
{
cout<<"======================"<
cout<<"1 - view all nodes"<
cout<<"2 - add node"<
cout<<"3 - delete node"<
cout<<"4 - find node"<
cout<<"5 - edit node"<
cout<<"6 - reverse chain"<
cout<<"0 - exit"<
cout<<"======================"<
}
void runsub5()
{
Chain link;
int pos,data,choice,data_new;
while(choice!=0)
{
show();
cout<<"select...";
cin>>choice;
switch(choice)
{
case 1:
cout<
break;
case 2:
cout<<"input data and pos...";
cin>>data>>pos;
link.insert(data,pos);
cout<
break;
case 3:
cout<<"input delete data...";
cin>>data;
link.del(data);
cout<
break;
case 4:
cout<<"input find data...";
cin>>data;
pos=link.find(data);
if(pos!=-1)
cout<<"find in pos:"<
else
cout<<"not find."<
break;
case 5:
cout<<"input old data and new data...";
cin>>data>>data_new;
link.editor(data,data_new);
cout<
break;
case 6:
cout<<"in 6"<
link.reverse();
cout<
break;
default:
break;
}
}
}
阅读(1061) | 评论(0) | 转发(0) |