fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node{
  5. int val;
  6. struct node *next;
  7. }Node;
  8.  
  9. Node *head=NULL;
  10.  
  11. Node* createN(int x){
  12. Node *newnode;
  13. newnode=(Node*)malloc(sizeof(Node));
  14. newnode->val=x;
  15. newnode->next=NULL;
  16. return newnode;
  17. }
  18.  
  19. void freeL(){
  20. Node *p;
  21. while(head!=NULL){
  22. p=head->next;
  23. free(head);
  24. head=p;
  25. }
  26. }
  27.  
  28. void printL(){
  29. Node *p=head;
  30. while(p!=NULL){
  31. printf("%d ",p->val);
  32. p=p->next;
  33. }
  34. printf("\n");
  35. }
  36.  
  37. void makeL(int n,int a[]){
  38. int i;
  39. Node *p,*q;
  40. head=createN(a[0]);
  41.  
  42. for(i=1;i<n;i++){
  43. p=head;
  44. q=createN(a[i]);
  45.  
  46. if(p->val>=a[i]){
  47. q->next=head;
  48. head=q;
  49. } else {
  50. while(p->next!=NULL&&p->next->val<a[i]) p=p->next;
  51. q->next=p->next;
  52. p->next=q;
  53. }
  54. }
  55. }
  56.  
  57. int main(void){
  58. int i,n;
  59. int *a;
  60. scanf("%d",&n);
  61. a=(int*)malloc(sizeof(int)*n);
  62.  
  63. for(i=0;i<n;i++) scanf("%d",&a[i]);
  64.  
  65. makeL(n,a);
  66. printL();
  67. freeL();
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5324KB
stdin
8
21 55 5 13 8 2 34 3
stdout
2 3 5 8 13 21 34 55