// ex4.h: interface for the ex4 class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_EX4_H__54A3647D_5049_4203_A4E5_E8650CD08322__INCLUDED_)
#define AFX_EX4_H__54A3647D_5049_4203_A4E5_E8650CD08322__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include<iostream>
using namespace std;
class ChainNode{
friend class Chain;
public:
int data ;
ChainNode *link;
};
class Chain{
friend class ChainIterator;
public:
Chain(){first=0;}
~Chain();
bool isEmpty() const {return first==0;}
int length() const;
bool find(int k,int x) const;
int search(int x) const;
Chain& Delete(int k,int x);
Chain& insert(int k,const int x);
void output(ostream& out) const;
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) const{
if(k<1) return false;
ChainNode *current=first;
int index=1;
while(index<k){
current=current->link;
index++;
}
if(current){
x=current->data;
return true;
}
return false;
}
int Chain::search(int x) const{
ChainNode *current=first;
int index=1;
while(current->data!=x){
current =current->link;
index++;
}
if(current)
return index;
else return 0;
}
void Chain::output(ostream& out) const{
ChainNode *current;
for(current=first;current;current=current->link)
out<<current->data<<" ";
}
ostream operator<<(ostream& out,const Chain& x){
x.output(out);
return out;
}
Chain& Chain::Delete(int k,int x){
if(k<1||!first)
{}//throw OutOfBounds();
ChainNode *p =first;
if(k==1)
{first=first->link;}
else{
ChainNode *q=first;
for(int index=1;index<k-1&&q;index++)
{ q=q->link;}
if(!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){
if(k<0){}// throw OutOfBounds();
ChainNode *p=first;
for(int index=1;index<k&&p;index++)
p=p->link;
if(k>0&&!p){}// throw OutOfBounds();
ChainNode* y=new ChainNode;
y->data=x;
if(k){
y->link=p->link;
p->link=y;
}
else{
y ->link=first;
first=y;
}
return *this;
}
class ChainIterator{
public:
int* Initialize(const Chain& c){
location=c.first;
if(location) return (&location->data);
else return 0;
}
int* Next(){
if(!location) return 0;
location =location->link;
if(location)
return &location->data;
else return 0;}
private:
ChainNode *location;
};
#endif // !defined(AFX_EX4_H__54A3647D_5049_4203_A4E5_E8650CD08322__INCLUDED_)
- 1
- 2
- 3
前往页