fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node{
  4. int data;
  5. node* next;
  6. node(int value)
  7. { data=value;
  8. next=nullptr;
  9. }
  10. };
  11.  
  12. class linkedlist{
  13. private:
  14. node* head;
  15.  
  16. node* reverse(node *currenthead,int part)
  17. {
  18. node* current=currenthead;
  19. node* save=nullptr;
  20. node* prev=nullptr;
  21. int count=0;
  22. while(count<part&& current!=nullptr)
  23. {
  24. save=current->next;
  25. current->next=prev;
  26. prev=current;
  27. current=save;
  28. count++;
  29. }
  30. if(save!=nullptr)
  31. {
  32. currenthead->next=reverse(save,part);
  33. }
  34. return prev;
  35. }
  36. public:
  37. linkedlist()
  38. {
  39. head=nullptr;
  40. }
  41.  
  42. void add(int val)
  43. {
  44. node *newnode=new node(val);
  45. if(!head)
  46. {
  47. head=newnode;
  48. newnode->next=nullptr;
  49. return;
  50. }
  51.  
  52. node* temp=head;
  53. while(temp->next!=nullptr)
  54. {
  55. temp=temp->next;
  56. }
  57. temp->next=newnode;
  58. newnode->next=nullptr;
  59.  
  60. }
  61.  
  62. void reverseinprt(int part)
  63. {
  64. head=reverse(head,part);
  65. }
  66. void display()
  67. {
  68. node* temp=head;
  69. while(temp)
  70. {
  71. cout<<temp->data<<" ";
  72. temp=temp->next;
  73. }
  74. }
  75. };
  76.  
  77. int main()
  78. {
  79. int len,partial;
  80. cin>>len>>partial;
  81. linkedlist l1;
  82. cout<<"Enter the list data"<<endl;
  83. for(int i=0;i<len;i++)
  84. {
  85. int m;cin>>m;
  86. l1.add(m);
  87. }
  88. l1.display();
  89. cout<<endl;
  90. l1.reverseinprt(partial);
  91. l1.display();
  92. return 0;
  93. }
  94.  
Success #stdin #stdout 0.01s 5304KB
stdin
7 7
1 3 6 8 9 2 10
stdout
Enter the list data
1 3 6 8 9 2 10 
10 2 9 8 6 3 1