C++ 单链表头插法以及区间删除

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

//有头结点单链表 
struct Node{
	int date;
	Node* next;
};

//初始化链表
Node* init(){
	Node* head = new Node;//申请一个Node类型的空间  返回一个地址 
	head->date = 0;
	head->next = NULL;	//头节点
	return head;
} 

//头插法
void insertList(Node* head, int ele){
	Node* cur = new Node();
	cur->date = ele; //数据赋值到cur节点的数据域 
	cur->next = head->next;	
	head->next = cur;
} 

//创建链表
void createList(Node* head, int low, int high){
	for(int i=low; i<=high; i++){
		insertList(head,i);
	}
}

//打印链表
void printList(Node* head){
	Node* p = head->next;
	while(p != NULL){
		cout<<p->date<<" ";
		p = p->next;
	}
	cout<<endl;
} 

//区间删除
void deleteElement(Node *head, int min, int max){
	Node *p = head->next; //用于移动,指向头指针下一个即第一个节点 
	Node *pr = head;	//用于存放删除节点的下一个位置 
	while(p != NULL){
		if(p->date<=max && p->date>=min){
			pr->next = p->next;	//pr->next存放p的后继节点地址,此时pr的指向并没有变 
			delete p;	//释放当前节点空间,删除 
			p = pr->next;	//指向删除节点的下一个(pr刚刚保存的位置) 
		}else{
			pr = pr->next; //当前节点不是要删除的,那么这俩都往下移一个 
			p = p->next;
		}
	}
} 

int main(){
	
	Node *head = init();
	
	insertList(head,20);
	printList(head);
	
	createList(head,0,20); 
	
	printList(head);
	
	deleteElement(head,5,10);	//删除5-10的元素 
	printList(head);
	
	return 0;
}

在这里插入图片描述

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

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/103756501