Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. // C++ program to count occurrences in a linked list
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. /* Link list node */
  6. class Node {
  7. public:
  8.     int data;
  9.     Node* next;
  10. };
  11.  
  12. /* Given a reference (pointer to pointer) to the head  
  13. of a list and an int, push a new node on the front  
  14. of the list. */
  15. void push(Node** head_ref, int new_data)
  16. {
  17.     /* allocate node */
  18.     Node* new_node = new Node();
  19.  
  20.     /* put in the data */
  21.     new_node->data = new_data;
  22.  
  23.     /* link the old list off the new node */
  24.     new_node->next = (*head_ref);
  25.  
  26.     /* move the head to point to the new node */
  27.     (*head_ref) = new_node;
  28. }
  29.  
  30. /* Counts the no. of occurrences of a node  
  31. (search_for) in a linked list (head)*/
  32. int count(Node* head, int search_for)
  33. {
  34.     Node* current = head;
  35.     int count = 0;
  36.     while (current != NULL) {
  37.         if (current->data == search_for)
  38.             count++;
  39.         current = current->next;
  40.     }
  41.     return count;
  42. }
  43.  
  44. /* Driver program to test count function*/
  45. int main()
  46. {
  47.     /* Start with the empty list */
  48.     Node* head = NULL;
  49.  
  50.     /* Use push() to construct below list  
  51.     1->2->1->3->1 */
  52.     push(&head, 1);
  53.     push(&head, 3);
  54.     push(&head, 1);
  55.     push(&head, 2);
  56.     push(&head, 1);
  57.  
  58.     /* Check the count function */
  59.     cout << "count of 1 is " << count(head, 1);
  60.     return 0;
  61. }
  62.  
  63. // This is code is contributed by rathbhupendra
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement