01list.h
#ifndef LIST_H
#define LIST_H 1
class List{
struct Node{
T data;
Node* next;
// Node* prev;//如果倒序只需要将一个节点的前后指针交换
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);//前插
List& push_back(const T& d);//尾插
int size()const;
Node*& getptr(int pos);//找链表中指向指定位置的指针
void insert(const T& d, int pos);//在任意位置插入
void travel()const;//遍历
void clear();//清空这个链表
~List();
void erase(int pos);//有效位置为0~size()-1
void remove(const T& d);
int find(const T& d)const;
void set(int pos, const T& d);
bool empty()const{return head==NULL;}
const T& front()const{if(empty())throw "空";return head->data;}
const T& back()const;
};
#endif
</span>
01list.cpp
#include <iostream>
using namespace std;
typedef int T;
#include "01list.h"
void List::push_front(const T& d){//前插
insert(d,0);
}
List& List::push_back(const T& d){//尾插
insert(d,size());
return *this;
}
int List::size()const{
return len;
}
List::Node*& List::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 List::insert(const T& d, int pos){//在任意位置插入
Node*& pn = getptr(pos);
Node* p = new Node(d);
p->next = pn;
pn = p;
++len;
}
void List::travel()const{//遍历
Node* p = head;
while(p!=NULL){
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
void List::clear(){//清空这个链表
while(head!=NULL){
Node* p = head->next;
delete head;
head = p;
}
len = 0;
}
List::~List(){
clear();
}
void List::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 List::remove(const T& d){
int pos;
while((pos=find(d))!=-1)
erase(pos);
}
int List::find(const T& d)const{
int pos = 0;
Node* p = head;
while(p){
if(p->data==d) return pos;
p = p->next; ++pos;
}
return -1;
}
void List::set(int pos, const T& d){
if(pos<0||pos>=size()) return;
getptr(pos)->data = d;
}
const T& List::back()const{
if(empty())throw "空";
Node* p=head;
while(p->next!=NULL)
p = p->next;
return p->data;
}
main.cpp
#include <iostream>
using namespace std;
typedef int T;
#include "01list.h"
int main()
{
List l;
l.push_back(1).push_back(2).push_front(3);
l.travel();
}