#include <iostream>
#include <iomanip>
#include <string.h>
#include <cmath>
#include <algorithm>//算法头文件
#include <fstream>
#include <cstdlib>
#include <vector>
#include <sstream>
using namespace std;
//模版类实现单链表
//一个类就是一个节点,头结点
template<typename T>class Node{
protected:
T data;//数据域
Node* next; //指针域
public:
Node(){ init(); }
//初始化
void init();
//头插法
void insertPre(T ele);
//遍历
void print();
//查找元素
int find(T ele);
//删除元素
void delEle(T ele);
//区间删除
void del(T min, T max);
//删除链表中某元素前面的元素
void del3( T ele);
//链表的拷贝
void copy(Node *head);
//创建链表
void createList(T low, T high);
};
//初始化
template<typename T> void Node<T>::init(){
this->data = 0;
this->next = NULL;
}
//头插法
template<typename T> void Node<T>::insertPre(T ele){
Node* cur = new Node;
cur->data = ele;
cur->next = this->next;
this->next = cur;
}
//遍历
template<typename T> void Node<T>::print(){
Node *p = this->next;
while(p!=NULL){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
//创建链表
template<typename T> void Node<T>::createList(T low, T high){
for(T i=low; i<=high; i++){
this->insertPre(i);
}
}
//查找元素
template<typename T> int Node<T>::find(T ele){
Node* p = this->next;
while(p!=NULL){
if(p->data == ele){
return 1;
}
p = p->next;
}
return -1;
}
//删除元素
template<typename T> void Node<T>::delEle(T ele){
Node* p = this->next;
Node* pr = this;
while(p!=NULL){
if(p->data == ele){
pr->next = p->next;
delete p;
p = p->next;
}else{
p = p->next;
pr = pr->next;
}
}
}
//区间删除
template<typename T> void Node<T>::del(T min, T max){
Node* p = this->next;
Node* pr = this;
while(p!=NULL){
if(p->data>=min && p->data<=max){
pr->next = p->next;
delete p;
p = pr->next;
}else{
p = p->next;
pr = pr->next;
}
}
}
//删除链表中某元素前面的元素
template<typename T> void Node<T>::del3(T ele){
Node* pr2 = this;//当前元素的要删除元素的前驱
Node* pr1 = this->next;//要删除的元素
Node* p = this->next->next;//当前元素
while(p!=NULL){
if(p->data == ele){
pr2->next = p;
delete pr1;
return ;
}else{
p = p->next;
pr1 = pr1->next;
pr2 = pr2->next;
}
}
}
//链表的拷贝
template<typename T> void Node<T>::copy(Node* head){
//一个类调用此方法,所以不用申请头结点的内存空间
Node* pb = this;
Node* pa = head->next;
while(pa!=NULL){
Node* cur = new Node;
cur->data = pa->data;
//尾插法向新表插入元素
cur->next = NULL;
pb->next = cur;
pb = pb->next;
pa = pa->next;
}
}
int main(){
Node<int> head;
head.createList(1,10);
head.print();
cout<<head.find(6)<<endl;
head.del(1,5);
head.print();
head.insertPre(3);head.insertPre(3);
head.print();
head.del3(10);
head.print();
head.delEle(3);
head.print();
Node<int> headb;
headb.copy(&head);
headb.print();
return 0;
}
C++ 类模版实现单链表的增删改查和链表拷贝
猜你喜欢
转载自blog.csdn.net/qq_42363032/article/details/103795269
今日推荐
周排行