单链表基础操作C++实现

最近在复习数据结构,就把单链表的基础操作过了一篇

Node.h头文件:

template<class T>
struct Node {
	T val;
	Node<T> *next;
	Node() {}
	Node(T nVal) {
		val = nVal;
		next = 0;
	}	
}; 
单链表类文件:

#include <iostream>
#include "Node.h"
#include <stdexcept>


using namespace std;

template<class T>
class SingleLinkList {	
private:
	int size;
	Node<T> *head;
	Node<T> *tail;
	Node<T> *getPointerAt(int pos) {	//返回pos位置的指针 
		Node<T> *pNode = 0;
		if(pos < 0 || pos > size-1)
			throw out_of_range("The position is out of range!");
		else {
			pNode = head;
			for(int i = 1; i <= pos; i++)
				pNode = pNode->next;		 
		}
		return pNode;
	}
public:
	SingleLinkList() {		// 构造函数 
		head = tail = 0;
		size = 0;
	}
	// add向单链表的尾部添加节点 
	void add(T nval) {
		Node<T> *pNode = new Node<T>(nval);
		if(!head) {			// 若链表为空 
			head = pNode;
			tail = pNode;
		}
		else {
			tail->next = pNode;
			tail = pNode;			
		}
		size++;	
	}
	// insertAt在指定位置插入节点
	void insertAt(int pos, T nval) {
		if(pos < 0 || pos > size)
			throw out_of_range("The position is out of range!");
		if(pos == size) {
			add(nval);	
		} 
		else if(pos == 0) {
			Node<T> *pNode = new Node<T>(nval);
			pNode->next = head;
			head = pNode;
			size++;
		}
		else {
			Node<T> *pNode = new Node<T>(nval);
			Node<T> *qNode = getPointerAt(pos-1);	//找到pos位置的前一个指针 
			pNode->next = qNode->next;
			qNode->next = pNode;	
			size++;		
		}	
	}
	// removeAt删除指定位置的节点 
	void removeAt(int pos) {
		if(size==0)
			throw runtime_error("the list is empty!");
		if(pos< 0 || pos >size-1)
			throw out_of_range("The position is out of range");
		if(size==1) {
			delete head;			
		} 
		else if(pos == 0) {
			Node<T> *p = head;
			head = head->next;
			delete p;		
		} 
		else {
			Node<T> *p = getPointerAt(pos-1);
			Node<T> *q= getPointerAt(pos);
			p->next = q->next;
			delete q;	
			if(pos == size-1)
				tail = p;
		}
		size--;
	}
	// 删除链尾节点 
	void remove() {
		removeAt(size-1);
	}
	// 判断链表是否为空 
	bool isEmpty() {
		return size==0? true : false;
	}
	// 返回链表大小 
	int sizeV() {
		return size;
	}
	// 返回链首元素 
	T getHeadVal() {
		if(size == 0)
			throw runtime_error("The list is empty!");
		return head->val;
	}
	// 返回链尾元素 
	T getTailVal() {
		if(size==0)
			throw runtime_error("The list is empty!");
		return tail->val;
	}
	// 清空链表 
	void clear() {
		while(head) {
			Node<T> *tmp = head->next;
			delete head;
			head = tmp; 
		}
		tail = 0;
		size = 0;
	}
	// 返回fval所在下标,-1表示没有找到 
	int find(T fval) {
		int index = 0;
		Node<T> *p = head;
		while(p) {
			if(p->val == fval)
				return index;
			index++;
			p = p->next;	
		}
		return -1;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值