fork download
  1. /*
  2. Median of a Sorted Linked List
  3. Given a sorted singly list of integers, return the median value.
  4. Example
  5. Input: 1 ⇒ 3 ⇒ 4 ⇒ 5 ⇒ 6 ⇒ 6 ⇒ 9
  6. Output: 5
  7.  
  8. Input: 1 ⇒ 3 ⇒ 4 ⇒ 5 ⇒ 6 ⇒ 6 ⇒ 8 ⇒ 9
  9. Output: 5.5
  10.  
  11.  
  12. */
  13.  
  14. // time complexity = O(n);
  15. // space complexity = O(1);
  16.  
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. struct Node{
  21. int data;
  22. Node* next;
  23. Node(int x) : data(x) , next(NULL) {}
  24. };
  25.  
  26. void insert(Node*& head , int val){
  27. if(!head){
  28. head = new Node(val);
  29. return;
  30. }
  31.  
  32. Node* temp = head;
  33. while(temp->next){
  34. temp = temp->next;
  35. }
  36. temp->next = new Node(val);
  37. }
  38.  
  39. double findmedian(Node* head){
  40. Node* slow = head;
  41. Node* fast = head;
  42. Node* prev = NULL;
  43.  
  44. while(fast && fast->next){
  45. prev = slow;
  46. slow = slow->next;
  47. fast = fast->next->next;
  48. }
  49.  
  50. if(fast == NULL){
  51. return double((prev->data + slow->data) / 2.0);
  52. }
  53.  
  54. return slow->data;
  55. }
  56. int main() {
  57.  
  58. Node* head = NULL;
  59.  
  60. int arr[]={1};
  61. int n = sizeof(arr) / sizeof(arr[0]);
  62.  
  63. for(int i = 0 ; i<n ; i++){
  64. insert(head,arr[i]);
  65. }
  66. cout<<"Median is :"<< findmedian(head);
  67. return 0;
  68. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
Median is :1