OneCompiler

linked list

147

*/Write a program to implement a linked list using structure and functions to do the following:
make a new node, insert first (add at front), display (print) elements of linked list, count the number of nodes in linked list, sum values (elements) inside the linked list.
*/

#include <iostream>
using namespace std;
struct node {
int number;
node* next;
};
//Make new node
node* make_new_node(int x)
{
node* p;
p = new node; p->number = x; p->next = NULL; return p;
}
//Insert in beginning (add at front)
node* insert_begin(node * p)
{
int x;
cout << "Enter value in new node \n"; cin >> x;
node* temp;
temp = make_new_node(x);
temp->next = p;
p = temp;
return p;
}
//Display (print) node elements
void display_list(node * p)
{
node *curr;
if(p == NULL)
cout<<"NO nodes found /n";
else
{
cout<<"\n data in the nodes are:";
curr = p;
while(curr !=NULL)
{
cout<<curr->number<<endl;
curr= curr->next;
}
}

}
int count(node* p)
{
node* curr;
curr = p;
int countN = 0;
while(curr!=NULL) {
countN++;
curr = curr->next;
}
return countN;
}
//sum of elements (values) inside the linkedlist
int summation(node* p)
{
node* curr;
curr = p;
int sum = 0;
while (curr != NULL) {
sum += curr->number; curr = curr->next;
}
return sum;
}
int main()
{
node* p;
p = NULL;
int x, n,nums,sumE;
cout << "\n Enter x value to make a new node: ";
cin >> x;
p = make_new_node(x);
display_list(p);
cout << "\n How much you want to add nodes at front ? ";
cin >> n;
for (int i = 0; i < n; i++)
p = insert_begin(p); display_list(p);
nums = count(p);
cout << "count: " << nums<<endl;
sumE = summation(p);
cout << "summation: " << sumE << endl;
return 0;

}