单链表的有序插入

#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;
}

int main(){

	Node *head = init();
	
	for(int i=10; i>=1; i--){
		insertBySort(head,i);
	}
	
	print(head);
	
	return 0;
}
发布了167 篇原创文章 · 获赞 52 · 访问量 6946

猜你喜欢

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