fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class node{
  5. public:
  6. int data;
  7. node* next;
  8.  
  9. node(int val)
  10. {
  11. data=val;
  12. next=NULL;
  13. }
  14. };
  15.  
  16. void insertAtHead(node* &head, int val)
  17. {
  18. node* n=new node(val);
  19. n->next=head;
  20. head=n;
  21. }
  22.  
  23. void insertAtTail(node* &head, int val){
  24. node* n = new node(val);
  25.  
  26. if(head==NULL){
  27. head=n;
  28. return;
  29. }
  30.  
  31. node* temp=head;
  32. while(temp->next!=NULL){
  33. temp=temp->next;
  34. }
  35. temp->next=n;
  36.  
  37. }
  38.  
  39. bool search(node* head,int val){
  40. node* temp=head;
  41. while (temp!=NULL)
  42. {
  43. if(temp->data==val){
  44. cout<<"true"<<endl;
  45. return true;
  46. }
  47. temp=temp->next;
  48. }
  49. cout<<"false"<<endl;
  50. return false;
  51. }
  52.  
  53. void deleteAtHead(node* &head){
  54. node* todelete=head;
  55. head=head->next;
  56.  
  57. delete todelete;
  58. }
  59.  
  60. void deletion(node* &head,int val){
  61. if(head == NULL){
  62. return;
  63. }
  64. if(head->next == NULL){
  65. deleteAtHead(head);
  66. return;
  67. }
  68.  
  69. node* temp=head;
  70.  
  71. while (temp->next->data != val)
  72. {
  73. temp=temp->next;
  74. }
  75.  
  76. node* todelete=temp->next;
  77. temp->next=temp->next->next;
  78.  
  79. delete todelete;
  80.  
  81. }
  82.  
  83. node* reverse(node* &head){
  84. node* prevptr=NULL;
  85. node* currptr=head;
  86. node* nextptr;
  87.  
  88. while(currptr!=NULL){
  89. nextptr=currptr->next;
  90. currptr->next=prevptr;
  91.  
  92. prevptr=currptr;
  93. currptr=nextptr;
  94. }
  95.  
  96. return prevptr;
  97. }
  98.  
  99. //reverse linkedlist recursively
  100. node* reverseRecursive(node* &head){
  101. if(head==NULL|| head->next==NULL){
  102. return head;
  103. }
  104.  
  105. node* newhead= reverseRecursive(head->next);
  106. head->next->next=head;
  107. head->next=NULL;
  108.  
  109. return newhead;
  110. }
  111. void display(node* head){
  112. node* temp=head;
  113. while(temp!=NULL){
  114. cout<<temp->data<<"->";
  115. temp=temp->next;
  116. }
  117. cout<<"NULL"<<endl;
  118. }
  119.  
  120.  
  121. int main(){
  122. node* head=NULL;
  123.  
  124. insertAtTail(head,1);
  125. insertAtTail(head,2);
  126. insertAtTail(head,3);
  127. display(head);
  128. insertAtHead(head,5);
  129. insertAtHead(head,4);
  130. display(head);
  131. search(head,5);
  132. deletion(head,5);
  133. display(head);
  134. node* newhead= reverseRecursive(head);
  135. display(newhead);
  136.  
  137. return 0;
  138. }
Success #stdin #stdout 0s 5580KB
stdin
Standard input is empty
stdout
1->2->3->NULL
4->5->1->2->3->NULL
true
4->1->2->3->NULL
3->2->1->4->NULL