fork download
  1. #include<iostream>
  2. using namespace std;
  3. class node{
  4. public:
  5. int data;
  6. node *next;
  7. node(int d){
  8. data = d;
  9. next = NULL;
  10. }
  11. };
  12.  
  13. void insertAtTail(node *&head, int data){
  14. if(head==NULL){
  15. head= new node(data);
  16. return;
  17. }
  18. node *tail = head;
  19. while(tail->next!=NULL){
  20. tail=tail->next;
  21. }
  22. tail->next=new node(data);
  23. return;
  24. }
  25. void buildInput(node *&head){
  26. int data;
  27. cin>>data;
  28. while(data!=-1){
  29. insertAtTail(head,data);
  30. cin>>data;
  31. }
  32. }
  33.  
  34. //racer technique
  35. node *midPoint(node *head){
  36. if(head==NULL || head->next==NULL){
  37. return head;
  38. }
  39. node *slow =head;
  40. node *fast = head->next;
  41. while (fast!=NULL && fast->next==NULL){
  42.  
  43. fast=fast->next->next;
  44. slow=slow->next;
  45. }
  46. return slow;
  47. }
  48.  
  49. void print(node *head){
  50. //node *temp=head;
  51. while(head!=NULL){
  52. cout<<head->data;
  53. head=head->next;
  54. }
  55. }
  56. int main(){
  57. node *head=NULL;
  58. buildInput(head);
  59. node *m= midPoint(head);
  60. cout<<m->data;
  61. //print(head);
  62. return 0;}
  63.  
Time limit exceeded #stdin #stdout 5s 5932KB
stdin
Standard input is empty
stdout
Standard output is empty