Try to search your question here, if you can't find : Ask Any Question Now ?

Linked List Will Not print max value

HomeCategory: stackoverflowLinked List Will Not print max value
craig asked 4 weeks ago

The following code will not print the last line which displays the maximum element in the linked list below.

In the following code, I sum the linked list, print the entire linked list, print the length of the linked list, and would like to print the maximum value found in the linked list.

For some reason, the compiler does not print the last line.

``````#include <iostream>
#include <stdio.h>
using namespace std;

struct Node{ //if you want to convert to class, you need to assign access specifiers to public since they're private on default

int data;
struct Node *next;

}*first = NULL;

void create(int A[], int n)
{
struct Node *t; //create a temporary pointer t
struct Node *last; //pointer, points to the last node - helps me add a new node at the END of a linked list
//as of now, the linked list is empty, so we must create the first node!

first = new Node;//create new node on the heap, and first will be pointing on that new node
first -> data = A[0]; // Assign first the first element on the array
first -> next = NULL;//Should point to a null value as it is the only element on the list to start/currently
last = first; //last points on first node

for (int i = 1; i <n; i++)// i starts at element 1 since first has been assigned the 1st element in the array
{
t = new Node; //create a new node
t->data = A[i]; //fill up the data of t from A[i] which will be iterated through and assigned to data
t->next = NULL; // the next node should be pointing to NULL, as there is nothing at the moment when the iteration begins that it is initially pointing to

last -> next = t;
last = t;
}
}

int length (struct Node *p)
{
int l = 0;
while (p)
{
l++;
p = p->next;
}
return l;
}

int sum (struct Node *p){
int s= 0;
while(p){
s+=p->data;
p = p->next;
}
return s;
}

int max (struct Node *p){
int max = -32767;
while(p){
if(p->data > max){
max = p->data;
p = p->next;
}
}
return max;
}

void display (struct Node *p)
{
while (p != 0 )
{
cout<<p->data<<" ";
cout<<p->next<<" ";
p = p->next;
}
}

int main() {

int A [] = {1,2,3,18,5, 6, 7};

create (A,7);
display(first);
cout<<endl;
cout<<"The length of the linked list (the number of nodes) is: "<< length(first)<<endl;
cout<<"The sum of the linked list values (nodes) is: "<< sum(first)<<endl;
cout<<"The maximum value in the linked list (of the nodes) is: "<< max(first)<<endl;

return 0;
}
``````

What am I doing wrong?

1 Answers
Best Answer
Mannu answered 4 weeks ago
Your Answer

2 + 12 =

WP Facebook Auto Publish Powered By : XYZScripts.com