文章

19

粉丝

225

获赞

68

访问

57.9k

头像
c-头插法
P1015 贵州大学机试题
发布于2023年3月26日 09:07
阅读数 3.0k

 先对数组进行冒泡排序,然后头插法创建链表,最后就链表遍历输出即可,也可以用尾插法啦。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node{
  4. struct node*next;
  5. int data;
  6. };
  7. struct node* create(int a[],int len){
  8. int i;
  9. struct node*head=(struct node*)malloc(sizeof(struct node));
  10. struct node*t=(struct node*)malloc(sizeof(struct node));
  11. t=NULL;
  12. for(i=0;i<len;i++){
  13. struct node*p=(struct node*)malloc(sizeof(struct node));
  14. p->data=a[i];
  15. p->next=t;
  16. t=p;
  17. head->next=t;
  18. }
  19. return head;
  20. }
  21. int main(){
  22. int a[5];
  23. int i,j,t;
  24. struct node*head;
  25. for(i=0;i<5;i++)
  26. scanf("%d",&a[i]);
  27. for(i=0;i<5;i++){
  28. for(j=0;j<5-i-1;j++){
  29. if(a[j]<a[j+1]){
  30. t=a[j];
  31. a[j]=a[j+1];
  32. a[j+1]=t;
  33. }
  34. }
  35. }
  36. head=create(a,5);
  37. head=head->next;
  38. while(head!=NULL){
  39. printf("%d ",head->data);
  40. head=head->next;
  41. }
  42. return 0;
  43. }

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发