数据结构--链表

  • 存储一大波数的时候,我们通常使用的是数组,但有时候数组显得不够灵活,比如下 面这个例子。 有一串已经从小到大排好序的数 2 3 5 8 9 10 18 26 32。现需要往这串数中插入 6使其得 到的新序列仍符合从小到大排列。如我们使用数组来实现这一操作,则需要将 8和 8后面的 数都依次往后挪一位。
  • 上面的操作显然很耽误时间,如果使用链表则会快很多。
  • 链表的插入:
  • 定义每个结点:。左边的部分用来存放具体的数值,那么用一个整型变量就可以;右边的部分需要存储下一个结点的地址,可以用指针来实现(也称为后继指针) 。
  • 如下:
 struct node {   
  int data;    
  struct node *next; 
   }; 

  • 代码:
 #include<iostream>
 #include<stdio.h>
 #include<stdlib.h>
using namespace std;
struct node{
int data;
struct node*next;
};
int main(){
  struct node *head;
  head=NULL;
  struct node *p,*q,*t;
  int n,a;cin>>n;
  for(int i=1;i<=n;i++){
      cin>>a;
       p=(struct node *)malloc(sizeof(struct node));
      p->data=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->data>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){
    cout<<t->data<<" ";
    t=t->next;
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值