链表与模拟链表

xiaoxiao2021-02-28  70

正常的链表

#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; }  

转载请注明原文地址: https://www.6miu.com/read-74427.html

最新回复(0)