#include <iostream>
using namespace std;
typedef int T;
class List{
//结点类,内部类
struct Node{
T d;
Node* next;
Node(const T& d):d(d),next(){}
//~Node(){cout << "~Node("<<d<<")"<<endl;}
};
Node* head;
int sz;
public:
List():head(),sz(){}
~List(){clear();}
//从头插入
void insert(const T& d){
Node* pn = new Node(d);
pn->next = head;
head = pn;
sz++;
}
//指定位置插入
void insert(const T& d, int pos){
if(pos<0||pos>sz) pos=0;
if(pos==0){
insert(d);
return;
}
Node* pn = new Node(d);
Node* p = head;
for(int i=0; i<pos-1; i++){
p = p->next;
}
pn->next = p->next;
p->next = pn;
sz++;
}
//清空
void clear(){
Node* p = head;
while(p){
head = head->next;
delete p;
p = head;
}
sz=0;
}
//打印
void travel(){
Node* p = head;
while(p){
cout << p->d << ' ';
p = p->next;
}
cout << endl;
}
//指定位置删除
void erase(int pos){
if(pos<0||pos>=sz)throw "out_of_pos";
if(pos==0){
Node* p = head;
head = head->next;
delete p;
sz--;
return;
}
Node* p = head;
for(int i=0; i<pos-1; i++){
p = p->next;
}
Node* q = p->next;
p->next = q->next;
delete q;
sz--;
}
};
C++实现链表结构
最新推荐文章于 2021-05-19 18:32:05 发布