链表(实现插入一个数)

时间:2022-07-24
本文章向大家介绍链表(实现插入一个数),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在存储一大波数时,使用数组显得不够灵活,如在排好序的一个序列中插入一个数,使用数组来实现时,需要把插入位置后面的所有数都后移。

这样的操作很浪费时间,但是用链表的话,只需要修改插入位置的指针即可。

代码实现如下:

#include<bits/stdc++.h>

using namespace std;

struct node{
	int date;
	struct node *next;
};

int main(){
	struct node *head,*p,*q,*t;
	int n;
	cin>>n;
	head = NULL;
	int a; 
	for(int i=1;i<=n;i++){
 		cin>>a;
 		p = (struct node *)malloc(sizeof(struct node));
 		p->date = a;
 		p->next = NULL;
 		if(head == NULL) head = p;
 		else q->next = p;
 		
 		q=p;
	}
	cin>>a;//读入待插入的数
	t = head;
	while(t!=NULL){
		if(t->next->date > a){
			p = (struct node *)malloc(sizeof(struct node));
			p -> date = a;
			p -> next = t->next;
			t -> next = p;
			break;
		}
		t = t->next;
	}
	t = head;
	while(t!=NULL){
		cout << t->date<<" ";
		t = t -> next;
	} 
	return 0;
}