前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >链表(实现插入一个数)

链表(实现插入一个数)

作者头像
杨鹏伟
发布2020-09-10 23:54:11
4580
发布2020-09-10 23:54:11
举报
文章被收录于专栏:ypwypw

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

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

在这里插入图片描述
在这里插入图片描述

代码实现如下:

代码语言:javascript
复制
#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;
} 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档