C++ 类实现单链表的增删改查和链表拷贝

#include <iostream>
#include <iomanip>
#include <string.h>
#include <cmath>
#include <algorithm>//算法头文件
#include <fstream>
#include <cstdlib>
#include <vector>
#include <sstream>
using namespace std;

//一个类看作成一个节点,头结点

class Node{
	protected:
		int data;
		Node *next;
	public:
		Node(){
			init();
		}
		
		//初始化
		void init();
		//头插法 
		int insertPre(int ele);
		//遍历
		void print(); 
		//查找元素
		int find(int ele);
		//删除元素
		void delEle(int ele);
		//区间删除
		void del(int min, int max);
		//删除链表中某元素前面的元素
		void del3( int ele);
		//链表的拷贝
		void copy(Node *head);
		//创建链表
		void createList(int low, int high);
}; 

//初始化,有头结点单链表
void Node::init(){
	this->data = 0;
	this->next = NULL;
} 

//头插法 
int Node::insertPre(int ele){
	Node *cur = new Node;
	cur->data = ele;
	cur->next = this->next;
	this->next = cur;
}
//创建链表
void Node::createList(int low, int high){
	for(int i=low; i<=high; i++){
		insertPre(i);
	}
}
//遍历
void Node::print(){
	Node *p = this->next;
	while(p!=NULL){
		cout<<p->data<<"  ";
		p = p->next;
	}
	cout<<endl;
} 

//区间删除
void Node::del(int min, int 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;
		}
	}
}

//查找元素
int Node::find(int ele){
	Node* p = this->next;
	while(p!=NULL){
		if(p->data == ele){
			return 1;
		}
		p = p->next;
	} 
	return 0;
}

//删除元素
void Node::delEle(int ele){
	Node* p = this->next;
	Node* pr = this;
	while(p!=NULL){
		if(p->data == ele){
			pr->next = p->next;
			delete p;
			p = pr->next;
		}else{
			p = p->next;
			pr = pr->next;
		}
	}
}

//链表的拷贝
void Node::copy(Node *head){
	Node* p_b = this;
	Node* p_a = head->next;
	while(p_a != NULL){
		Node* cur = new Node;
		cur->data = p_a->data;
		cur->next = NULL;
		p_b->next = cur;
		p_b = p_b->next;
		p_a = p_a->next;
	} 
}

//删除链表中某元素前面的元素 
void Node::del3( int ele){
	Node* p = this->next->next;
	Node* pr1 = this->next;
	Node* pr2 = this;
	while(p!=NULL){
		if(p->data == ele){
			pr2->next = p;
			delete pr1;
			return ;
		}else{
			p = p->next;
			pr1 = pr1->next;
			pr2 = pr2->next;
		}
	}
}

int main(){

	Node headA;
	
	headA.createList(1,10);
	
	headA.print();
	
	cout<<headA.find(1)<<endl;
	
	headA.insertPre(11);
	
	headA.print();
	
	headA.del(5,10);
	
	headA.print();
	
	headA.delEle(11);
	
	headA.print();
	
	Node headB;
	headB.copy(&headA);
	headB.print();

	
	return 0;
}

在这里插入图片描述

发布了167 篇原创文章 · 获赞 52 · 访问量 6942

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/103795257
今日推荐