Algorithm 3_C language: Knowing that the nodes in the dynamic singly linked list L are arranged in ascending integer values, try to write an algorithm to insert the nodes with the value x into the table L so that L is still in order.

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode {
	int elem;
	struct LNode* next;
}LNode, * linklist;
void LNode_create(linklist& L);
void insert_N(linklist& L);
void display(linklist L);
int main()
{
	linklist L;
	LNode_create(L);
	insert_N(L);
	display(L);
}
void LNode_create(linklist& L)//创建链表
{
	int N, i;
	linklist p, q;
	L = (linklist)malloc(sizeof(LNode));
	L->next = NULL;
	p = L;
	printf("请输入你要建立的数组元素个数:\n");
	scanf_s("%d", &N);
	printf("请按递增顺序输入数组\n");
	for (i = 0; i < N; i++)
	{
		q = (linklist)malloc(sizeof(linklist));
		scanf_s("%d", &q->elem);
		q->next = NULL;
		p->next = q;
		p = q;
	}
	free(p);
}
void insert_N(linklist& L)
{
	int N, t = 1;
	linklist Lhead, p = L, q, last;
	Lhead = (linklist)malloc(sizeof(LNode));
	Lhead->elem = NULL;
	Lhead->next = L;
	last = Lhead;
	printf("请输入要插入的整数:\n");
	scanf_s("%d", &N);
	if (N < p->elem)
	{
		q = (linklist)malloc(sizeof(LNode));
		q->elem = N;
		q->next = p;
		L = q;
	}
	else
	{
		while (p->next)
		{
			if (N >= p->elem && N <= p->next->elem)
			{
				q = (linklist)malloc(sizeof(LNode));
				q->elem = N;
				q->next = p->next;
				p->next = q;
				break;
			}
			p = p->next;
		}
		if (N > p->elem)
		{
			q = (linklist)malloc(sizeof(LNode));
			q->elem = N;
			p->next = q;
			q->next = NULL;
		}

	}
}
void display(linklist L)
{
	while (L)
	{
		printf("%d ", L->elem);
		L = L->next;
	}
}

Guess you like

Origin blog.csdn.net/qq_51224492/article/details/110559351