链表的实现

#include <iostream>
using namespace std;
typedef int T;


class List{
struct Node{


T  data;
Node * next;
Node(const T&d d=T());data(d),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_back(const T& d)
{
insert(d,size());
return *this;
}

int size()const{
/*int cnt = 0;
Node * p = head;
while(p!=NULL)
{
++cnt;
p = p->next;
}
return cnt;*/
return len;

}
Node* &getptr(int pos)//连标中指向zhen定位置的指针
{
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;
delete head;
head = p;
}
}
~List()
{
clear();
}

void erase(int pos){
if(pos < 0 || pos>=size()) return;
Node *& pn = getptr(pos);
Node * p = pn;
pn = pn->next;
delete p;
--len;
}
     } 
};


int main()
{
List l;
l.push_front(5);
l.push_front(8);
l.pudh_front(20);
l.insert(9,2);
l.insert(6,100);
l.insert(7,10);
l.insert(1,2);
l.push_back(10).push_back(15).travel();
l.travel();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值