#include <iostream>
using namespace std;
typedef int T;
class List{
struct Node{
T data;
Node* next;
Node(const T& d=T()):data(d),next(0){}//零初始化
};
Node* head;//頭指標,用來保存頭節點的地址
int len;
public:
List():head(NULL),len(0){ }
void push_front(const T& d){//前插
insert(d,0);
}
List& push_back(const T& d){//尾插
insert(d,size());
return *this;
}
int size()const{
return len;
}
Node*& getptr(int pos){//找鏈表中指向指定位置的指標
if(pos<0||pos>size()) pos=0;
if(pos==0) return head;
Node* p = head;
for(int i=1; i<pos; i++)
p = p->next;
return (*p).next;
}
void insert(const T& d, int pos){//在任意位置插入
Node*& pn = getptr(pos);
Node* p = new Node(d);
p->next = pn;
pn = p;
++len;
}
void travel()const{//遍歷
Node* p = head;
while(p!=NULL){
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
void clear(){//清空這個鏈表
while(head!=NULL){
Node* p = head->next;
// cout << "delete " << head << endl;
delete head;
head = p;
}
len = 0;
}
~List(){
// cout << this << "*******" << head << endl;
clear();
}
void erase(int pos){//有效位置為0~size()-1
if(pos<0||pos>=size()) return;
Node*& pn = getptr(pos);
Node* p = pn;
pn = pn->next;
delete p;
--len;
}
void remove(const T& d){
int pos;
while((pos=find(d))!=-1)
erase(pos);
}
int find(const T& d)const{
int pos = 0;
Node* p = head;
while(p){
if(p->data=https://bbs.csdn.net/topics/=d) return pos;
p = p->next; ++pos;
}
return -1;
}
void set(int pos, const T& d){
if(pos<0||pos>=size()) return;
getptr(pos)->data = d;
}
bool empty()const{return head==NULL;}
T front()const{if(empty())throw "空";return head->data;}
T back()const{
if(empty())throw "空";
Node* p=head;
while(p->next!=NULL)
p = p->next;
return p->data;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/123309.html
標籤:基礎類
上一篇:求解。。。0-1背包問題
