fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class node{
  5. public:
  6. int data;
  7. node* next;
  8.  
  9. //Constructor
  10. node(int d){
  11. data = d;
  12. next = NULL;
  13. }
  14. };
  15.  
  16. void insertAtHead(node*&head,int data){
  17. node*n = new node(data);
  18. n->next = head;
  19. head = n;
  20. }
  21.  
  22. int length(node*head){
  23.  
  24. int len=0;
  25. while(head!=NULL){
  26. head = head->next;
  27. len += 1;
  28. }
  29. return len;
  30. }
  31.  
  32. void insertAtTail(node*&head,int data){
  33.  
  34. if(head==NULL){
  35. head = new node(data);
  36. return;
  37. }
  38. node*tail = head;
  39. while(tail->next!=NULL){
  40. tail = tail->next;
  41. }
  42. tail->next = new node(data);
  43. return;
  44. }
  45.  
  46.  
  47.  
  48.  
  49.  
  50. void print(node*head){
  51. //node*temp = head;
  52.  
  53. while(head!=NULL){
  54. cout<<head->data<<" ";
  55. head = head->next;
  56. }
  57. cout<<endl;
  58. }
  59.  
  60.  
  61.  
  62. node* append(node* head , int k){
  63.  
  64. int len = length(head) - k;;
  65. node* temp = head;
  66. int count=0;
  67. while(temp && count<len-1){
  68. temp=temp->next;
  69. count++;
  70. }
  71.  
  72. //cout<<temp->data;
  73. node* prevKth = temp;
  74. //cout<<prevKth->data;
  75.  
  76. node* kThNode = temp->next;
  77. //cout<<kThNode->data;
  78. temp = kThNode;
  79. while(temp->next)
  80. temp=temp->next;
  81.  
  82. //cout<<temp->data;
  83. temp->next = head;
  84. head = kThNode;
  85.  
  86. prevKth->next = NULL;
  87. return head;
  88. }
  89.  
  90. int main() {
  91.  
  92.  
  93. node*head1 = NULL;
  94. //node* head2 = NULL;
  95. int x=0;
  96. int n1 =0,k=0;
  97. cin>>n1;
  98. for(int i=0;i<n1;i++){
  99. cin>>x;
  100. insertAtTail(head1,x);
  101. }
  102. cin>>k;
  103.  
  104.  
  105. // print(head);
  106. head1 = append(head1 , k);
  107. print(head1);
  108. return 0;
  109. }
Success #stdin #stdout 0s 15240KB
stdin
7
1 2 2 1 8 5 6
3
stdout
8 5 6 1 2 2 1