I am trying to implement the a dot product calculation formula into the linked list implementation on my below code and I am having the below error:
request for member 'add_node' in 'B', which is of pointer type 'linked_list {aka node*}' (maybe you meant to use '->' ?)
How can I clear that and make working code? I don't want to use classes as well
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
int index;
node *next;
};
typedef node* linked_list;
node *head = NULL;
node *tail = NULL;
void add_node(int i,int n)
{
node *tmp = new node;
tmp->index = i;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void display(node *head)
{
while(head!=0)
{
cout << head->index <<" ," << head->data << endl;
display(head->next);
break;
}
}
int main()
{
linked_list A;
A.add_node(2,7);
A.add_node(4,5);
A.add_node(7,8);
A.add_node(9,4);
linked_list B;
B.add_node(3,5);
B.add_node(4,6);
B.add_node(9,5);
int product=0;
while(A!=0 && B!=0)
{
if(A->index == B->index)
{
product = product + A->data * B->data;
A=A->next;
B=B->next;
}
else if(A->index < B->index)
{
A=A->next;
}
else
{
B=B->next;
}
}
return product;
return 0;
}
The error tells you what you need to know. linked_list is a pointer. You need to use the -> operator, not the dot operator.
Additionally, your node struct does not contain a method called add_node(). In fact it doesn't contain any methods at all.
#include <iostream>
using namespace std;
struct node
{
int data;
int index;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int i,int n)
{
node *tmp = new node;
tmp->index = i;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
node* gethead()
{
return head;
}
};
void display(node *head)
{
while(head!=0)
{
cout << head->index <<" ," << head->data << endl;
display(head->next);
break;
}
}
int main()
{
linked_list A;
A.add_node(2,7);
A.add_node(4,5);
A.add_node(7,8);
A.add_node(9,4);
linked_list B;
B.add_node(3,5);
B.add_node(4,6);
B.add_node(9,5);
display(A.gethead());
display(B.gethead());
int product=0;
node *current_a = A.gethead();
node *current_b = B.gethead();
while(current_a != 0 && current_b!=0)
{
if(current_a->index == current_b->index)
{
product = product + current_a->data * current_b->data;
current_a=current_a->next;
current_b=current_b->next;
}
else if(current_a->index < current_b->index)
{
current_a=current_a->next;
}
else
{
current_b=current_b->next;
}
}
cout<<"\nDot Product : "<< product<<endl;
return 0;
}
enter code here
Related
Hello fellow programmers, the below code gives segmentation fault. This code aims to insert an element at the end of a linked list. I tried using print statements to debug it. I think the error is in passing the linked list pointer to insert() function. Please tell me how can I correct it. Thanks in advance.
Below is the code:
#include <iostream>
using namespace std;
class node {
public:
int data;
node *next;
node(int data) {
this->data = data;
this->next = NULL;
}
};
class linked_list {
public:
node *head;
linked_list() {
this->head = NULL;
}
};
void insert(node **head, int data);
void print(linked_list *L);
int main() {
int N;
linked_list *A = new linked_list();
cout << "N: ";
cin >> N;
for(int i=0; i<=N-1; i++) {
int t;
cin >> t;
insert(&(A->head), t);
}
print(A);
return 0;
}
void insert(node **head, int data) {
node *temp = new node(data);
if(*head == NULL) {
*head = temp;
return;
} else {
node *t = *head;
while(t->next != NULL) {
t=t->next;
}
t->next = temp;
return;
}
}
void print(linked_list *L) {
node * t = L->head;
while(t!=NULL) {
cout << t->data << " ";
t = t->next;
}
return;
}
main.cpp:42:14: error: using the result of an assignment as a
condition without parentheses [-Werror,-Wparentheses]
if(*head = NULL) {
~~~~~~^~~~~~
main.cpp:42:14: note: place parentheses around the assignment to
silence this warning
if(*head = NULL) {
^
( )
main.cpp:42:14: note: use '==' to turn this assignment into an
equality comparison
if(*head = NULL) {
^
==
1 error generated.
You're using assignment where you intended to do a comparison.
I'm trying to implement a stack using a doubly linked list. I know that the functions for my stack class (push, pop) should contain calls to member functions of my doubly linked list class, but I'm having trouble actually implementing that.
dlist.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "dlist.hpp"
using namespace std;
void dlist::appendNodeFront(int shares, float pps){
Node *n = new Node(shares, pps);
if(front == NULL){
front = n;
back = n;
}
else {
front->prev = n;
n->next = front;
front = n;
}
}
void dlist::appendNodeBack(int shares, float pps){
Node *n = new Node(shares, pps);
if(back == NULL){
front = n;
back = n;
}
else {
back->next = n;
n->prev = back;
back = n;
}
}
void dlist::display(){
Node *temp = front;
cout << "List contents: ";
while(temp != NULL){
cout << temp->value << " ";
temp = temp->next;
}
cout << endl;
}
void dlist::display_reverse(){
Node *temp = back;
cout << "List contents in reverse: ";
while(temp != NULL){
cout << temp->value << " ";
temp = temp->prev;
}
cout << endl;
}
void dlist::destroyList(){
Node *T = back;
while(T != NULL){
Node *T2 = T;
T = T->prev;
delete T2;
}
front = NULL;
back = NULL;
}
stack.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include "stack.hpp"
using namespace std;
stack::stack(){
int i;
for(i = 0; i < 1500; i++){
shares[i] = 0;
pps[i] = 0;
}
first = 0;
}
void stack::push(int num, float price){
if(first ==(1500-1)){
cout << "Stack is full" << endl;
return;
}
first++;
shares[first] = num;
pps[first] = price;
return;
}
void stack::pop(int *num, float *price){
if(first == -1){
cout << "Stack is empty" << endl;
return;
}
num = &shares[first];
price = &pps[first];
cout << shares[first] << endl;
cout << pps[first] << endl;
shares[first] = 0;
pps[first] = 0;
first--;
return;
}
Should the push function in stack basically be a call to appendNodeFront() or appendNodeback()? Any help or advice is greatly appreciated!
You can create a stack class, then use linked list class as its container. In a linked list class there is virtually no limit to the number of items, so you add artificial limit to make it work like a stack. In a linked list, items can be added/removed anywhere in the list, you can limit add/remove the tail node only to make it work like stack. The example below demonstrate the usage.
Node that this is purely a programming exercise. Stack is relatively primitive compared to Doubly-linked list. Encapsulating a linked-list inside stack has no advantage. Also note, I declared all members as public for the sake of simplifying the problem, you may want to change some members to protected/private
#include <iostream>
#include <fstream>
#include <string>
using std::cout;
class Node
{
public:
Node *prev;
Node *next;
int shares;
float pps;
Node(int vshares, float vpps)
{
shares = vshares;
pps = vpps;
prev = next = nullptr;
}
};
class dlist
{
public:
Node *head;
Node *tail;
dlist()
{
head = tail = nullptr;
}
~dlist()
{
destroy();
}
void push_back(int shares, float pps)
{
Node *node = new Node(shares, pps);
if (head == NULL)
{
head = tail = node;
}
else
{
tail->next = node;
node->prev = tail;
tail = node;
}
}
void destroy()
{
Node *walk = head;
while (walk)
{
Node *node = walk;
walk = walk->next;
delete node;
}
head = tail = nullptr;
}
};
class stack
{
public:
int maxsize;
int count;
dlist list;
stack(int size)
{
count = 0;
maxsize = size;
}
void push(int num, float price)
{
if (count < maxsize)
{
list.push_back(num, price);
count++;
}
}
void pop()
{
Node *tail = list.tail;
if (!tail)
{
//already empty
return;
}
if (tail == list.head)
{
//only one element in the list
delete tail;
list.head = list.tail = nullptr;
count--;
}
else
{
Node *temp = list.tail->prev;
delete list.tail;
list.tail = temp;
list.tail->next = nullptr;
count--;
}
}
void display()
{
Node *walk = list.head;
while (walk)
{
cout << "(" << walk->shares << "," << walk->pps << ") ";
walk = walk->next;
}
cout << "\n";
}
};
int main()
{
stack s(3);
s.push(101, 0.25f);
s.push(102, 0.25f);
s.push(103, 0.25f);
s.push(104, 0.25f);
s.display();
s.pop();
s.display();
return 0;
}
I am new to linked list..My simple code is to create linked list and insert nodes at the end and traverse it..
My problems are-
1)-Every time insert function is called,head pointer gets null
2)-not working right while going in show function..
Please help..Thanks in advance
#include<iostream>
#include<malloc.h>
using namespace std;
struct linkedList
{
int value;
linkedList *next;
};
linkedList* head = NULL;
void insert(linkedList* head, int data)
{
linkedList *ptr;
linkedList *node;
node = (linkedList*) malloc(sizeof(struct linkedList));
node->value = data;
node->next = NULL;
if (head == NULL)
{
head = node;
}
else
{
ptr = head;
while (ptr != NULL)
{
ptr = ptr->next;
}
ptr = node;
}
}
void show(struct linkedList *head)
{
struct linkedList *ptr;
ptr = head;
while (ptr != NULL)
{
cout << ptr->value << endl;
ptr = ptr->next;
}
}
int main()
{
int size = 5;
int array[size];
for (int i = 0; i < 5; i++)
{
cout << "Enter value" << endl;
cin >> array[i];
insert(head, array[i]);
}
show(head);
}
In your insert() function:
when head is NULL, you are assigning the new node to the local head parameter, which is not updating the caller's head variable. That is why your global head variable is always NULL. This is because you are passing the head parameter by value, so you are assigning the new node to a copy, not the original. You need to pass the parameter by reference/pointer instead.
when head is not NULL, you are not traversing the nodes correctly to find the tail node, so ptr is always NULL after the traversal. You are not setting the next field of the tail node at all.
Also, your main() is leaking the allocated nodes.
Try something more like this instead:
#include <iostream>
struct linkedNode
{
int value;
linkedNode *next;
};
void insertValue(linkedNode* &head, int data)
{
linkedNode *node = new linkedNode;
node->value = data;
node->next = NULL;
if (!head)
{
head = node;
}
else
{
linkedNode *ptr = head;
while (ptr->next)
{
ptr = ptr->next;
}
ptr->next = node;
}
}
void showValues(linkedNode *head)
{
linkedNode *ptr = head;
while (ptr)
{
std::cout << ptr->value << std::endl;
ptr = ptr->next;
}
}
void freeValues(linkedNode* &head)
{
linkedNode *ptr = head;
head = NULL;
while (ptr)
{
linkedNode *next = ptr->next;
delete ptr;
ptr = next;
}
}
int main()
{
linkedNode* mylist = NULL;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
insertValue(mylist, value);
}
showValues(mylist);
freeValues(mylist);
return 0;
}
That being said, if you keep track of the tail node in the list, inserts at the end would be much faster and efficient since you would not need to traverse the list at all:
#include <iostream>
struct linkedNode
{
int value;
linkedNode *next;
linkedNode(int data)
value(data), next(NULL)
{
}
};
struct linkedList
{
linkedNode *head;
linkedNode *tail;
linkedList()
: head(NULL), tail(NULL)
{
}
~linkedList()
{
linkedNode *ptr = head;
while (ptr)
{
linkedNode *next = ptr->next;
delete ptr;
ptr = next;
}
}
void insert(int data)
{
linkedNode *node = new linkedNode(data);
if (!head)
head = node;
if (tail)
tail->next = node;
tail = node;
}
void showValues()
{
linkedNode *ptr = head;
while (ptr)
{
std::cout << ptr->value << std::endl;
ptr = ptr->next;
}
}
};
int main()
{
linkedList mylist;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
mylist.insert(value);
}
mylist.showValues();
return 0;
}
In which case, you could just throw all of this away and use the standard std::list class instead:
#include <iostream>
#include <list>
#include <algorithm>
void showValue(int value)
{
std::cout << value << std::endl;
}
void showValues(const std::list<int> &values)
{
std::for_each(values.begin(), values.end(), showValue);
/* or, if you are using C++11:
std::for_each(values.begin(), values.end(),
[](int value){ std::cout << value << std::endl; }
);
*/
}
int main()
{
std::list<int> mylist;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
mylist.push_back(value);
}
showValues(mylist);
return 0;
}
I'm trying to create a basic singly-linked list using a separate Node class and LinkedList class. I barely know what I'm doing as I've just started learning C++, so any help would be greatly appreciated.
The LinkedList part of the code runs on its own, but I'm sure there are some corrections to be made there too. My main problem is that, when trying to add to the linked list, I'm getting (at line 64 of LinkedList.h):
Exception thrown: read access violation. this->head was nullptr.
I'm using Microsoft Visual Studio 2015. Here's the code:
LinkedList.h (it's inline):
#pragma once
#include <iostream>
using namespace std;
class Node
{
private:
Node *next = NULL;
int data;
public:
Node(int newData) {
data = newData;
next = NULL;
}
Node() {
}
~Node() {
if(next)
delete(next);
}
Node(int newData, Node newNext) {
data = newData;
*next = newNext;
}
void setNext(Node newNext) {
*next = newNext;
}
Node getNext() {
return *next;
}
int getData() {
return data;
}
};
class LinkedList
{
private:
Node *head;
int size;
public:
LinkedList()
{
head = NULL;
size = 0;
}
~LinkedList()
{
}
void add(int numberToAdd)
{
head = new Node(numberToAdd, *head);
++size;
}
int remove()
{
if (size == 0) {
return 0;
}
else {
*head = (*head).getNext();
--size;
return 1;
}
}
int remove(int numberToRemove)
{
if (size == 0)
return 0;
Node *currentNode = head;
for (int i = 0; i < size; i++) {
if ((*currentNode).getData() == numberToRemove) {
*currentNode = (*currentNode).getNext();
return 1;
}
}
}
void print()
{
if (size == 0) {
return;
}
else {
Node currentNode = *head;
for (int i = 0; i < size; i++) {
cout << currentNode.getData();
currentNode = currentNode.getNext();
}
cout << endl;
}
}
};
List Tester.cpp
// List Tester.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList myList;
myList.add(4);
system("pause");
}
You are making copies where you should not:
This:
Node(int newData, Node newNext) {
data = newData;
*next = newNext;
}
should be:
Node(int newData, Node* newNext) {
data = newData;
next = newNext;
}
Because now this:
head = new Node(numberToAdd, *head);
becomes this:
head = new Node(numberToAdd, head);
and will work even if head is a null pointer. You may need to adjust your other code accordingly.
Your whole implementation is full of errors. It should look more like this instead:
#pragma once
#include <iostream>
class Node
{
private:
int data;
Node *next;
public:
Node(int newData, Node *newNext = NULL)
: data(newData), next(newNext)
{}
void setNext(Node *newNext) {
next = newNext;
}
Node* getNext() {
return next;
}
int getData() {
return data;
}
};
class LinkedList
{
private:
Node *head;
int size;
public:
LinkedList()
: head(NULL), size(0)
{
}
~LinkedList()
{
Node *currentNode = head;
while (currentNode)
{
Node *nextNode = currentNode->getNext();
delete currentNode;
currentNode = nextNode;
}
}
void add(int numberToAdd)
{
head = new Node(numberToAdd, head);
++size;
}
bool remove()
{
Node *currentNode = head;
if (!currentNode)
return false;
head = currentNode->getNext();
delete currentNode;
--size;
return true;
}
bool remove(int numberToRemove)
{
Node *currentNode = head;
Node *previousNode = NULL;
while (currentNode)
{
if (currentNode->getData() == numberToRemove)
{
if (head == currentNode)
head = currentNode->getNext();
if (previousNode)
previousNode->setNext(currentNode->getNext());
delete currentNode;
return true;
}
previousNode = currentNode;
currentNode = currentNode->getNext();
}
return false;
}
void print()
{
Node *currentNode = head;
if (!currentNode) return;
do
{
std::cout << currentNode->getData();
currentNode = currentNode->getNext();
}
while (currentNode);
std::cout << std::endl;
}
};
Which can then be simplified using the std::forward_list class (if you are using C++11 or later):
#pragma once
#include <iostream>
#include <forward_list>
#include <algorithm>
class LinkedList
{
private:
std::forward_list<int> list;
public:
void add(int numberToAdd)
{
list.push_front(numberToAdd);
}
bool remove()
{
if (!list.empty())
{
list.pop_front();
return true;
}
return false;
}
bool remove(int numberToRemove)
{
std::forward_list<int>::iterator iter = list.begin();
std::forward_list<int>::iterator previous = list.before_begin();
while (iter != list.end())
{
if (*iter == numberToRemove)
{
list.erase_after(previous);
return true;
}
++previous;
++iter;
}
return false;
}
void print()
{
if (list.empty()) return;
std::for_each(list.cbegin(), list.cend(), [](int data){ std::cout << data });
std::cout << std::endl;
}
};
What are use cases for self-referential types?
By self referential types, I mean:
class T {
T *ptr; // member variable that references the type of the class
};
It is one of the most efficient ways to build linked lists or tree
hierarchies.
#include <iostream>
class linked_ints {
public:
linked_ints() : next(nullptr), x(0) {}
linked_ints* next;
int x;
};
void print(linked_ints* b) {
if(b == nullptr) return;
do {
std::cout << b->x << std::endl;
} while((b = b->next));
}
int main()
{
linked_ints x, y, z;
x.next = &y; y.next = &z;
print(&x);
return 0;
}
One example I can think of are linked lists.
The example borrowed from here:
#include<iostream>
struct Node{
int data;
Node* next;
};
void InsertAfter(Node **head, int value){
if(*head==NULL){
Node* temp=NULL;
temp = new Node;
temp->data = value;
temp->next = NULL;
*head = temp;
}else{
Node *temp = new Node;
temp->data = value;
temp->next = (*head)->next;
(*head)->next = temp;
}
}
void DeleteAfter(Node **head){
if(*head==NULL){
return;
}else{
Node *temp = NULL;
temp = (*head)->next;
(*head)->next = (*head)->next->next;
delete temp;
temp=NULL;
}
}
int DeleteAll(Node **head,int value){
int count=0;
Node *p = NULL;
Node *q = (*head);
if(*head==NULL){
count =0;
}else{
while((q)!=NULL){
if((q)->data==value){
Node *temp = NULL;
temp = q;
if ( p!=NULL){
p->next = q->next;
}else{
(*head) = q->next;
}
q = q->next;
delete temp;
temp = NULL;
++count;
}else{
p = q;
q = q->next;
}
}
}
return count;
}
void DisplayList(Node *head){
if(head!=NULL){
std::cout << head->data << "\n";
while(head->next!=NULL){
std::cout << head->data << "\n";
head =
head->next;
}
std::cout << "\n\n";
}
int main(){
Node *head=NULL;
InsertAfter(&head,10);
InsertAfter(&head,10);
InsertAfter(&head,20);
InsertAfter(&head,10);
DisplayList(head);
DeleteAfter(&head);
DisplayList(head);
int a = DeleteAll(&head,10);
std::cout << "Number Of Nodes deleted
having value 10 = " <<
a <<"\n\n";
DisplayList(head);
return 0;
}