代码
#include <iostream>
using namespace std;
class List{
typedef int T;
struct Node{
int data;
Node* next;
//这种初始化成为0初始化,具有通用性
Node(const T& data = T(), Node* next = NULL)
:data(data),next(next){}
};
Node* head;//头指针,用来保存头结点的地址
int len;
public:
List():head(NULL),len(0){}
//void push_front(const T& d){//前插
// Node* p = new Node(d);
// p->next = head;
// head = p;
//}
List& push_front(const T& d){//前插
//等效写法
//Node* p = new Node(d);
//p->next = head;
//head = p;
insert(d, 0);
return *this;
}
List& push_back(const T& d){//后插
insert(d, size());
return *this;
}
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;
}
int size()const{//链表长度
//int cnt = 0;
//Node* p = head;
//while(p->next){
// ++cnt;
// p = p->next;
//}
//return cnt;
return len;
}
void insert(const T& d, int pos){//在任意位置插入
//pn = p.next 地址
Node*& pn = getPtr(pos);
Node* p = new Node(d);
//新元素的下一个元素指向原 p.next 指向的元素
p->next = pn;
//原来的 p.next 指向新元素
pn = p;
++len;
}
void erase(int pos){//按位置擦除
if(pos<0 || pos >len)
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){//按值查找
int pos = 0;
Node* p = head;
while(p){
if (p->data)
return pos;
p = p->next;
++pos;
}
return -1;
}
void travel()const{//遍历
Node* p = head;
while(p!=NULL){
cout << p->data << ' ';
p = p->next;
}
cout << endl << endl;
}
void set(const T& d, int pos){//按位置修改
if(pos<0 || pos >len)
return ;
getPtr(pos)->data = d;
}
bool empty()const{//判断为空
return head==NULL;
}
T front()const{//输出首值
if(empty())
throw "empty";
return head->data;
}
T back()const{//输出末值
if(empty())
throw "empty";
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
return p->data;
}
void clear(){//清空
while(head!=NULL){
Node* p = head->next;
delete head;
head = p;
}
}
~List(){
clear();
}
};
int main (){
List l;
cout << "sizeof(l1) = " << sizeof(l) << endl;
List l_1;
l_1.push_front(1);
l_1.push_front(2);
l_1.push_front(3);
l_1.push_front(4);
l_1.travel();
List l_2;
l_2.push_front(1).push_front(2).push_front(3).push_front(4);
l_2.travel();
getchar();
return 0;
}