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. void kthNode(node* head , int k){
  63.  
  64. if(k==0){
  65. head->data;
  66. return;
  67. }
  68. //int len = length(head) - k;
  69.  
  70. node* temp = head;
  71. int count=0;
  72. while(temp && count<k){
  73. temp=temp->next;
  74. count++;
  75. }
  76.  
  77. if(temp->next==NULL){
  78. cout<<temp->data;
  79. return;
  80. }
  81.  
  82. node* kth = head;
  83. while(temp){
  84. kth=kth->next;
  85. temp=temp->next;
  86. }
  87.  
  88.  
  89. cout<<kth->data;
  90.  
  91. }
  92.  
  93. int main() {
  94.  
  95.  
  96. node*head1 = NULL;
  97. //node* head2 = NULL;
  98. int x=0;
  99. int n1 =0,k=0;
  100. cin>>n1;
  101. for(int i=0;;i++){
  102. cin>>x;
  103. if(x==-1)
  104. break;
  105. insertAtTail(head1,x);
  106. }
  107. cin>>k;
  108.  
  109.  
  110.  
  111. // print(head);
  112. kthNode(head1 , k);
  113. //print(head1);
  114. return 0;
  115. }
Success #stdin #stdout 0s 15240KB
stdin
1 2 3 4 5 6 -1
3
stdout
4