function of adding a new element to list - list

I have a problem when trying to implement a program which adds a new element to an existing list. Here it is:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct person{ int v;
struct person *next;
};
void add(struct person *head, int n)
{ struct person *nou;
nou=(person*)malloc(sizeof(struct person));
nou->next=head;
head=nou;
nou->v=n;
}
int main()
{
struct person *head,*current,*nou;
head=NULL;
nou=(person*)malloc(sizeof(struct person));
nou->next=head;
head=nou;
nou->v=10;
add(head,14);
current=head;
while(current!=NULL)
{ cout<<current->v<<endl;
current=current->next;
}
return 0;
}
When i run it, it appears that there is only the element with the value 10 in it. What is the problem?

You need to pass in a pointer to the head pointer so that its value can be changed.
void add(struct person **head, int n)
{
struct person *nou;
nou=(person*)malloc(sizeof(struct person));
nou->next=*head;
*head=nou;
nou->v=n;
}
Call it like this:
add(&head,14);

Related

Class member pointer's property returns a random value

I am implementing a LinkedList in C++. After initializing the LinkedList, the value of the head is returned correctly (0). However, after calling another function from the LinkedList, the value of the head suddenly changes (825533248 is outputted). This seems strange, considering that I did not make any modifications to the head between initializing the LinkedList and calling the function.
Below is my class declaration (declaration.hpp):'
#include <iostream>
#include <fstream>
using namespace std;
class LinkedList
{
private:
Node *head;
public:
LinkedList(int v);
void insert(int v);
static void solution();
};
typedef struct Node
{
int val;
bool flag;
Node *next;
} Node;
And below is the implementation of my class:
#include <fstream>
#include <sstream>
#include "datastructure.hpp"
using namespace std;
void LinkedList::insert(int v)
{
cout << head->val << endl; // OUTPUTS 825533248
}
LinkedList::LinkedList(int v)
{
Node headNodeObject = {v, true, NULL};
head = &headNodeObject; // Convert head from object to pointer
}
void LinkedList::solution()
{
LinkedList linkedList = LinkedList(0);
// Test insertion
linkedList.insert(1);
}
Below is my main.cpp:
#include <iostream>
#include <string.h>
#include <datastructure.hpp>
using namespace std;
int main(int argc, char const *argv[])
{
LinkedList::solution();
}
Node headNodeObject = {v, true, NULL};
This object is stack-allocated, which means it's destroyed at the end of its scope: your constructor. Keeping a pointer on it and dereferencing that pointer after it's destroyed is Undefined Behavior (might display junk, might crash, ...). Make an heap-allocated object instead:
head = new Node {v, true, NULL};
BUT it means you'll need to delete it in your destructor (and properly freeing a linked list in the right order is a non-trivial operation), otherwise you'll get a memory leak.
My advice: use std::unique_ptr<Node> instead of Node*.

How do I fix my object initialization for a template BST class?

This problem occurs in my main.cpp:
using namespace std;
#include <iostream>
#include "BST.h"
#include "Packet.h"
int main()
{
BST test; // It occurs on this line!
Packet one(1, "testPacket", 1, 1);
system("Pause");
}
The error on that line says:
argument list for class template "BST" is missing
I don't know how to fix it. I just want to initialize the BST. How can I fix this error? I'm not very experienced with templates. Please help. My priority is fixing this glaring problem right now. Can I get help?
For reference purposes:
BST.h:
#ifndef BST_H
#define BST_H
using namespace std;
template <typename T>
class Node {
public:
Node() : rlink(nullptr), llink(nullptr) {}
~Node() {}
private:
T data;
Node *rlink, *llink;
};
template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node * root;
};
#endif
BST.cpp
#include "BST.h"
template <typename T>
BST<T>::BST() : root(nullptr) {}
template <typename T>
void BST<T>::insert(T data) {
if (root != nullptr) {
}
else {
cout << "NPTR" << endl;
}
}
Packet.h
#ifndef PACKET_H
#define PACKET_H
#include <string>
using namespace std;
class Packet {
public:
Packet(int partId, string description, double price, int partCount) :
partId(partId), description(description), price(price), partCount(partCount) {}
int getPartId() const { return partId; }
string getDescription() const { return description; }
double getPrice() const { return price; }
int getPartCount() const { return partCount; }
private:
int partId;
string description;
double price;
int partCount;
};
#endif
There are 2 problems.
The first is that Node needs to know what type T is, so you need to tell it when you use Node like this:
template <typename T>
class BST {
public:
BST();
void insert(T data);
private:
Node<T> * root;
};
Secondly, BST needs to know what its own type T is when you try to use it, so you need to do it like this:
BST<int> test; // Or whatever you are searching for in your tree. Doesn't have to be an int
P.S. Just heading this off now, you're probably going to need to implement BST in the header file. Failure to do so might cause linker problems.
P.P.S. I've been reading your comments on the original post, and what you actually probably need this instead:
BST<Packet> test; // Since you are searching for packets.

Linked List error assigning temp variable to first variable of list

So I have been working with linked lists and I am trying to assign temp variable to the first node in the list but it errors out
code where I set a temp node to list
Node *temp = NULL;
Node *found = NULL;
bool isfound = false;
temp = list;
the place where list defined in LinkedList class
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"
class LinkedList{
private:
Node *list;
Node *createNode();
Node *searchLocation(int);
public:
LinkedList();
~LinkedList();
void insertNode();
void deleteNode(int);
void printList();
void searchNode();
};
#endif
node header
#ifndef NODE_H
#define NODE_H
class Node{
public:
char lastName[20];
char firstName[20];
int idNumber;
Node *next;
Node *head;
Node(char a[], char b[], int i);
void printNode();
};
#endif
node class
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(char a[], char b[], int i){
*lastName = *a;
*firstName = *b;
idNumber = i;
}
void Node::printNode(){
cout<<lastName<<", "<<firstName<<": "<<idNumber<<endl;
}
error says can't convert from LinkedList* to Node* in assignment temp = list;
You haven't shown where you declare the list object, but from the error I can see it is of type LinkedList*.
If you want to point to the first node, then you have to assign
temp = list->list.
Of course since list is a private member of LinkedList, you cannot do this outside of the LinkedList class.
So you need to provide an accessor function that returns this node object.
Assuming that list is a LinkedList *, then temp = list->list; should work.

Variable undeclared in function

Hi I'm having a problem with global pointer being underclared in function.
Here is my code
#include <iostream>
using namespace std;
void push_l(int n);
struct elem{
int key;
elem *next;
} *left=NULL,*right=NULL;
void push_l(int n){
elem *p=left;
left=new elem;
left->key=n;
left->next=p;
if (right==NULL)right=left;
}
int main(){
push_l(5);
system "pause";
return 0;
}
This is one of the error messages I get - In function void push_l(int) left underclared
This is what you get for using namespace std; (std has a left too). And you don't even need iostream. The reference to left is ambiguous.
Do this:
#include <cstdlib>
struct elem{
int key;
elem *next;
} *left=NULL,*right=NULL;
void push_l(int n){
elem *p=left;
left=new elem;
left->key=n;
left->next=p;
if (right==NULL)right=left;
}
int main(){
push_l(5);
std::system("pause");
return 0;
}

Pointing to an object of the same type

I feel this question may be a bit trivial, but I simply cannot wrap my head around it. I currently have a class, Node, which is trying to point to what node occurs before the current node using the pointer prevNode. However I seem unable to access any variables within prevNode.
When running Main.cpp from the following code, it prints the result '15340756'. Where am I going wrong? Appologies as Im still a bit new to C++.
Node.h
#include "stdafx.h"
class Node
{
public:
Node();
void setPrevNode(Node n);
Node getPrevNode();
int i;
private:
Node *prevNode;
};
Node.cpp
#include "stdafx.h"
#include "Node.h"
Node::Node(){
i = 0;
}
void Node::setPrevNode(Node n){
prevNode = &n;
}
Node Node::getPrevNode(){
return *prevNode;
}
Main.cpp
#include "stdafx.h"
#include "Node.h"
int _tmain(int argc, _TCHAR* argv[])
{
Node nodes[] = {Node(), Node()};
nodes[0].i = 1;
nodes[1].setPrevNode(nodes[0]);
printf("%i", nodes[1].getPrevNode().i);
while(true){
}
return 0;
}
void setPrevNode(Node n);
Here setPrevNode is declared to take a copy of the node passed as an argument, and point to such node. After the function returns, the pointed to node no longer exist and what you get is undefined behavior.
What you want is to take the Node either as a reference or a pointer instead:
void setPrevNode(Node& n)
{
prevNode = &n;
}
void setPrevNode(Node* n)
{
prevNode = n;
}
On the same line, getPrevNode is defined to return a copy of the previous node. You most certainly want to return a reference here instead, although you can also return a pointer:
Node& getPrevNode()
{
return *prevNode;
}
Node* getPrevNode()
{
return prevNode;
}