链表与模拟链表

正常的链表

#include<cstdio>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct node{
	int data;
	struct node *next;
};
int main(){
	struct node *head,*p,*q,*t;
	int i,n,a;
	cin>>n;
	head=NULL;
	for(int i=0;i<n;i++){//链表的建立 
		cin>>a;//输入数据 
		p=(struct node*)malloc(sizeof(struct node));//动态申请一个空间,并用临时指针p来储存 
		p->data=a;
		p->next=NULL;
		if(head==NULL)//必须要有一个头节点 
		head=p;
		else
		q->next=p;
		q=p;//q才是最终储存的地方,它的头节点是head 
	}
	cin>>a;
	t=head;
	while(t!=NULL){//新建立一个链表节点 
		if(t->next==NULL||t->next->data>a){
			p=(struct node*)malloc(sizeof(struct node));
			p->data=a;
			p->next=t->next;//t的next变成p的next 
			t->next=p;//t则指向p 
			break;
		}
		t=t->next;
	}
	t=head;
	while(t!=NULL){
		cout<<t->data<<" ";
		t=t->next;
	}
}

模拟链表

用左右两个数组来储存

#include<cstdio>
#include<iostream>
using namespace std;
int main(){
	int data[200],right[200];
	int i,n,t,len;
	cin>>n;
	for(int i=1;i<=n;i++)
	cin>>data[i];
	len=n;
	for(int i=1;i<=n;i++){//构建初始模拟链表 
		if(i!=n)
		right[i]=i+1;//记录它的下一位的位置 
		else
		right[i]=0; //最后一个没有下一位 
	}
	len++;
	cin>>data[len];
	t=1;//从模拟链表头部开始遍历 
	while(t!=0){
		if(data[right[t]]>data[len]){
			right[len]=right[t];//新插入的数的结点标号等于比它大的数的序号 
			right[t]=len;
			break;
		}
		t=right[t];
	}
	t=1;
	while(t!=0){
		cout<<data[i];
		t=right[t];
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值