第15周 啊哈算法 链表:用指针链表和数组模拟链表

问题及代码:

/*
功能:链表中插入数据并输出所有数据 
*/
#include<stdio.h>
#include<stdlib.h>
struct node 
 {
   int date;
   struct node *next;
 };

 int main()
  {
    struct node *head,*p,*q,*t;
    int i,a,n;

    head=NULL;
    scanf("%d",&n);

    for(i=1;i<=n;i++)
     {
       scanf("%d",&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;
       }
t=head;
scanf("%d",&a);
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)
       {
        printf("%d",t->date);
        t=t->next;
        }
  getchar();getchar();
  return 0;
}

/*功能:同上,用数组模拟链表*/
#include<stdio.h>

int main()
 {
   int date[101],right[101];
   int i,n,t,len;

   scanf("%d",&n);
   for(i=1;i<=n;i++)
      scanf("%d",&date[i]);  
   len=n;
   
   //初始化right数组,right数组存放的是date的下标值
   for(i=1;i<=n;i++)
    {
      if(i!=n)
        right[i]=i+1;
      else
        right[i]=0; //表示最后一个  

   len++;//date添加一个数;
   scanf("%d",&date[len]);

   //链表头部开始遍历
   t=1;
   while(t!=0)
    {
      if(date[right[t]]>date[len])
        {
          right[len]=right[t];
          right[t]=len;
          break;
        }
       t=right[t];  
     }
    
     t=1;
     while(t!=0)
      {
        printf("%d",date[t]);
        t=right[t];
      }
     getchar();
     getchar();
     return 0;
   }
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值