#Adding Nodes or Data in a Linked List. Not Working?

5 messages · Page 1 of 1 (latest)

velvet iris
#

Hello, I was trying to add the data in the inputted Nodes for example, if I entered in 1 2 3 4 5,

it would add 1 + 2 + 3 + 4 + 5 = 15
but it just does not show the addNodes at all..

am I prepending wrong?

#include <iostream>
using namespace std;

struct Node{
    int data;
    struct Node* next;

};

void prepend(struct Node** head, int newData){
    struct Node* newNode = new Node;
    newNode->data = newData;
    newNode->next = (*head);
    (*head) = newNode;

}

void print(struct Node* head){
    while(head!=NULL){
        cout << head->data <<" ";
        head = head->next;

    }

}
float addNode(Node* head){
    int counter = 0;
    int sum = 0;
    
    struct Node*curr = head;
    while(curr!=NULL){
        counter++;
        sum += curr->data;
        curr = curr->next;
    }

return sum;

    }

int main(){
    int data, input;
    Node* head = NULL;

    for (int i=0; i<5; i++){
        cout<< "Input data: \n";
        cin>> input;
        prepend(&head, input);
    }
    
    print(head);
    cout <<endl;
    addNode(head);
    print(head);


}

finite starBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

cosmic hamlet
#
#include <iostream>

struct Node {
  int data;
  struct Node* next;
};

void prependAndRepoint(Node*& head, int newData) {
  Node* newNode = new Node;
  newNode->data = newData;
  newNode->next = head;
  head = newNode;
}

void print(Node* head) {
  while (head != NULL) {
    std::cout << head->data << " ";
    head = head->next;
  }
  std::cout << std::endl;
}

float sumNodes(Node* head) {
  int counter = 0;
  int sum = 0;

  Node* curr = head;
  while (curr != NULL) {
    counter++;
    sum += curr->data;
    curr = curr->next;
  }

  return sum;
}

int main() {
  int data, input;
  Node* head = NULL;

  for (int i = 0; i < 5; i++) {
    std::cout << "Input data: \n";
    std::cin >> input;
    prependAndRepoint(head, input);
  }

  print(head);
  std::cout << "Sum is " << sumNodes(head) << std::endl;
  print(head);
}
#

you're not printing what addNode(sumNode) is

#

passing by Node*& is easier to understand, you intend to modify the pointer