有序数列中插入一个数(C语言实现链表)

一个有序数列中插入一个数,用C语言实现链表。

输入

9
2 3 5 8 9 10 18 26 32
6

输出

2 3 5 6 8 9 10 18 26 32

代码

#include <stdio.h>
#include <stdlib.h>

//创建一个结构体用来表示链表的结点类型
struct node {
	int data;
	struct node *next;
}; 


int main()
{
    struct node *head,*p,*q,*t;
    int i,n,a;
    scanf("%d",&n);
    head = NULL;   //头指针为空
	for (i = 1; i<=n; i++){//读入n个数 
		scanf("%d",&a);
		//动态申请一个空间,用来存放一个结点,并用临时指针p指向这个结点
		p = (struct node *)malloc(sizeof(struct node));
		p -> data = a;//将数据存储到当前结点的data域中 
		p -> next = NULL;//设置当前结点的后继指针指向为空,也就是当前结点的下一个结点为空 
		if (head == NULL){
			head = p;//如果这是第一个结点,则将头指针指向这个结点 
		}
		else {
			q->next = p;//如果不是第一个创建的结点,则将上一个结点的后继指针指向当前结点 
		}
		q = p;//指针q也指向当前结点 
	}
    scanf("%d",&a);//读入待插入的数
	t = head;//从链表头开始遍历 
	while (t != NULL){//当没有到达链表尾的时候循环 
		if (t->next == NULL || t->next->data > a)
		//当前结点是最后一个结点或下一个结点的值大于a时插入 
		{
			p = (struct node *)malloc(sizeof(struct node));//申请内存用来存放新增的结点 
			p->data = a;
			p->next = t->next;//新增结点的后继指针指向当前结点的后继指针指向的结点 
			t->next = p;//当前结点的后继指针指向新增结点 
			break;
		}
		t = t->next;//继续遍历下一个结点 
	} 
	//输出链表中所有数 
	t = head;
	while (t != NULL){
		printf("%d ",t->data);
		t = t->next;//继续下一个结点 
	}
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/Gamer_Lee/article/details/81637510