fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node *next;
  8. };
  9.  
  10. struct node *head = NULL;
  11.  
  12. void appendNode(int data)
  13. {
  14. struct node *newnode = (struct node *)malloc(sizeof(struct node));
  15. newnode->data = data;
  16. newnode->next = NULL;
  17.  
  18. if(head == NULL)
  19. head = newnode;
  20. else
  21. {
  22. struct node *temp = head;
  23. while(temp->next)
  24. temp = temp->next;
  25. temp->next = newnode;
  26. }
  27. }
  28.  
  29. void displayNodes()
  30. {
  31. struct node *temp = head;
  32.  
  33. printf("HEAD->");
  34. if(temp)
  35. {
  36. while(temp)
  37. {
  38. printf("%d->",temp->data);
  39. temp = temp->next;
  40. }
  41. }
  42. printf("NULL");
  43. }
  44.  
  45. //REVERSING THE LINKEDLIST BY RECURSION
  46. void reverseListByRecursion(struct node *currNode)
  47. {
  48. if(currNode==NULL)
  49. return;
  50. else
  51. {
  52. reverseListByRecursion(currNode->next);
  53. printf("%d->",currNode->data);
  54. }
  55. }
  56.  
  57. //REVERSING THE LINKEDLIST BY USING POINTERS
  58. void reverseListByPointers()
  59. {
  60. struct node *p = head,
  61. *q = NULL,
  62. *r;
  63.  
  64. while(p!=NULL)
  65. {
  66. r = q;
  67. q = p;
  68. p = p->next;
  69. q->next = r;
  70. }
  71.  
  72. head = q;
  73. }
  74.  
  75. void findMidNode()
  76. {
  77. struct node *p=head,*q=p->next;
  78.  
  79. if(p==NULL)
  80. {
  81. printf("\n\nLinked List is empty!!!");
  82. return;
  83. }
  84. else if(q==NULL)
  85. {
  86. printf("\n\nMid node is: %d",p->data );
  87. return;
  88. }
  89. else
  90. {
  91. while(q!=NULL)
  92. {
  93. p = p->next;
  94. q = q->next->next;
  95. }
  96. printf("\n\nMid node is: %d",p->data);
  97. }
  98. }
  99.  
  100. int main()
  101. {
  102. appendNode(123);
  103. appendNode(234);
  104. appendNode(345);
  105. printf("\n\nActual LinkedList\n");
  106. displayNodes();
  107.  
  108. //REVERSING THE LINKEDLIST BY RECURSION
  109. printf("\n\nReversed LL by recursion\n");
  110. printf("HEAD->");
  111. reverseListByRecursion(head);
  112. printf("NULL");
  113.  
  114. //REVERSING THE LINKEDLIST BY USING POINTERS
  115.  
  116. reverseListByPointers();
  117. printf("\n\nReversed LL by pointers\n");
  118. displayNodes();
  119.  
  120. findMidNode();
  121.  
  122. return 0;
  123. }
Success #stdin #stdout 0.02s 1852KB
stdin
Standard input is empty
stdout

Actual LinkedList
HEAD->123->234->345->NULL

Reversed LL by recursion
HEAD->345->234->123->NULL

Reversed LL by pointers
HEAD->345->234->123->NULL

Mid node is: 234