C++实现链表结构

#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--;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值