单链表有序插入,插入后依然有序

#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 data;	//数据域 
	Node *next; //指针域 
};

//初始化单链表,即创建头指针
Node* init(){
	Node *head = new Node;
	head->data = 0;
	head->next = NULL;
	return head;
} 
//打印链表
void print(Node *head){
	//因为要移动指针,所以用一个指针指向,保留原来数据不变
	Node *p = head->next; //p指向链表
	while(p != NULL){
		cout<<p->data<<"  ";
		p = p->next;
	} 
	cout<<endl;
} 

void insertBySort(Node* head, int ele){
	Node* p = head;		//用于移动的节点   后继大节点 
	Node* pr = head;	//用于保存当前插入节点的前驱小节点 
	//先移动 
	while((p=p->next)!=NULL  && p->data<ele){
		pr = p; //这个循环结束后,就找到了当前节点的额前驱小节点和后继大节点 
	}
	Node* nl = new Node;
	nl->data = ele;
	nl->next = pr->next;
	pr->next = nl;
}

//有序单链表中有序插入  升序
void insert(Node* head, int ele){
	Node* p = head->next; //用于移动 
	Node* pr = head;	//指向判断节点的前驱节点 
	while(p!=NULL){
		//1 2 3 3
		//2
		if(p->data >= ele){//插入的元素小于等于链表里的 
			//此时p已经到比插入元素大的后继节点了
			Node* cur = new Node;
			cur->data = ele;
			cur->next = p;
			pr->next = cur; 
			return ;
		}else{
			p = p->next;
			pr = pr->next;
		}
	}
	//如果插入的元素比链表里的都大
	Node* cur = new Node;
	cur->data = ele;
	cur->next = p;
	pr->next = cur;
}

int main(){

	Node *head = init();
	
	for(int i=10; i>=1; i--){
		insertBySort(head,i);
	}
	
	print(head);
	
	insert(head,6);
	print(head);
	insert(head,0);
	print(head);
	insert(head,100);
	print(head);
	
	return 0;
}

在这里插入图片描述

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

猜你喜欢

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