fork(1) download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4.  
  5. typedef struct node
  6. {
  7. int info;
  8. struct node *next;
  9. }node;
  10.  
  11. node *getnode(int elem)
  12. {
  13. node *p=(node *)malloc(sizeof(node));
  14. p->info=elem;
  15. p->next=NULL;
  16. return p;
  17. }
  18.  
  19. void append(node **head,int elem)
  20. {
  21. node *temp;
  22. if((*head)==NULL)
  23. {
  24. (*head)=getnode(elem);
  25. }
  26. else
  27. {
  28. temp=(*head);
  29. while(temp->next!=NULL)
  30. temp=temp->next;
  31. temp->next=getnode(elem);
  32. }
  33. }
  34.  
  35. /**************** Displays the list ****************************/
  36. void display(node *head)
  37. {
  38. while(head)
  39. {
  40. printf(" %d ",head->info );
  41. head=head->next;
  42. }
  43. }
  44. /*************** Deletes the next node to p and returns it ******************/
  45. node *deleteNextNode(node **p)
  46. {
  47. node *q;
  48. q=(*p)->next;
  49. (*p)->next=q->next;
  50. return q;
  51. }
  52. /*********** Inserts a node q at the last node(at a head of the reversed list)*********************/
  53. void insertLastAtFirst(node **last,node *q)
  54. {
  55. q->next=(*last)->next;
  56. (*last)->next=q;
  57. }
  58.  
  59. void func(node **head,int n)
  60. {
  61. node *p,*q,*last;
  62. int i,term;
  63. last=*head;
  64. while(last->next!=NULL)
  65. last=last->next;
  66. //printf("\nLast=%d\n",last->info);
  67. p=(*head);
  68. if(n%2==0)
  69. term=(n/2)-1;
  70. else
  71. term=n/2;
  72.  
  73. for(i=0;i<term;i++)
  74. {
  75. if(p->next)
  76. {
  77.  
  78. q=deleteNextNode(&p);
  79. p=p->next;
  80. //printf("\nNode to be deleted %d now p pointing to %d\n",q->info,p->info);
  81. if(q!=last)
  82. insertLastAtFirst(&last,q);
  83. printf("\n");
  84. //display(*head);
  85. }
  86. }
  87. }
  88.  
  89.  
  90. int main()
  91. {
  92. node *head=NULL;
  93. int i,n,elem;
  94. printf("\nEnter the number of elements\n");
  95. scanf("%d",&n);
  96. printf("\nEnter the elements\n");
  97. for(i=0;i<n;i++)
  98. {
  99. scanf("%d",&elem);
  100. append(&head,elem);
  101. }
  102.  
  103. display(head);
  104. func(&head,n);
  105. printf("\n");
  106. display(head);
  107.  
  108. return 0;
  109. }
  110.  
Success #stdin #stdout 0s 2384KB
stdin
10
1 2 3 4 5 6 7 8 9 10
stdout
Enter the number of elements

Enter the elements
 1  2  3  4  5  6  7  8  9  10 




 1  3  5  7  9  10  8  6  4  2