Class Node: def __init__(self,initdata): self.data = initdata self.next = none C
ID: 3588422 • Letter: C
Question
Class Node:
def __init__(self,initdata):
self.data = initdata
self.next = none
Class OrderedList:
def __init__(self):
self.head = None
For an ordered linked-list, write an algorithm called count which will count the number of occurrences of a specific piece of data. First, you have to create the linked list using the following input (note: this should be an ordered list - how will we do this?).
2, 5, 10, 14, 18, 23, 23, 23, 25, 26, 29, 31, 35, 37.
Remember to count the duplicates.
Explanation / Answer
// C/C++ program to count occurrences in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts the no. of occurences of a node
(search_for) in a linked list (head)*/
int count(struct Node* head, int search_for)
{
struct Node* current = head;
int count = 0;
while (current != NULL)
{
if (current->data == search_for)
count++;
current = current->next;
}
return count;
}
// C/C++ program to count occurrences in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts the no. of occurences of a node
(search_for) in a linked list (head)*/
int count(struct Node* head, int search_for)
{
struct Node* current = head;
int count = 0;
while (current != NULL)
{
if (current->data == search_for)
count++;
current = current->next;
}
return count;
}