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.
Related
I need to define a class of linked list,List, in a way such that object of class can be defined in two ways,
List obj1 = L1();//head=0
List obj2 = L2(given_arr[], size of array) // I would be given an array, whose elements are elements of list
so, I need to form a construter for both,
for obj1, Its easy.
List(){head=0};
But I am not abe to do so for second type of object.
I tried to form a program for this.
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head;
int arr[];
List() { head = 0; }
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
int i;
head->val = arr[0];
for (i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[4] = {9, 89, 0, 43};
List* M = new List();
List* L = new List(barr[4], 4);
L->display();
return 0;
}
This program doesn't work. Please suggest a way to do so.
Make these changes to your main().
int main() {
int barr[] = {9, 89, 0, 43}; // No need to specify size if you're initializing
// List* M = new List(); // unused
// Your array is barr, barr[4] makes no sense. You also don't allocate the List,
// the list allocates
List L = List(barr, sizeof(barr) / sizeof(barr[0]);
L.display(); // -> to .
return 0;
}
This now compiles, but immediately segfaults. Simply running the program in the debugger shows a simple error. The line head->val = arr[0]; attempts to dereference a null pointer. Which takes us to the next thing. Use nullptr, not NULL or 0.
Your array constructor was over-complicated, you just need this:
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
Your addnode() function already handled an empty list. Fixing that, your code should run. I made a couple other small changes, mostly trimming cruft out. Here's your complete code:
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head = nullptr;
List() = default;
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[] = {9, 89, 0, 43};
List L = List(barr, sizeof(barr) / sizeof(barr[0]));
L.display();
return 0;
}
Whats wrong with this code?
I am writing this code to implement singly linked list using arrays but its not working. Im using code::blocks and its crashing on run time. Please help.
I must have missed out on something when it was taught in the class. xD
#include<iostream>
#include<stdio.h>
using namespace std;
class Node
{
int data;
Node *next;
public:
Node(int n)
{
data=n;
next=NULL;
}
friend class List;
};
class List
{
Node *listptr;
public:
void create();
void display();
};
void List::create()
{
Node *temp;
int n, num;
cout << "Enter number of nodes:" << endl;
cin >> n;
cout << "/nEnter the data" << endl;
for(int i=0; i<n; i++)
{
cin >> num;
Node *new_node=new Node(num);
if(listptr==NULL)
listptr=temp=new_node;
else
{
temp->next=new_node;
temp=temp->next;
}
}
}
void List::display()
{
Node *temp=listptr;
while(temp!=NULL)
{
cout << temp->data << "->";
temp=temp->next;
}
}
main()
{
List l1;
l1.create();
l1.display();
}
listptr not initialized, you can initialize in constructor.
List() {
listptr = 0;
}
Class List should be
class List
{
Node *listptr;
public:
List() {
listptr = 0;
}
void create();
void display();
};
Try following piece of code -
First Creating Node
class ListElement
{
int data;
ListElement* next;
public:
void set_element(int item) { data = item; }
int get_value() { return data; }
friend class List;
};
Another class for further operation
class List
{
ListElement *Start, *Tail, *New;
public:
List() { Start = Tail = New = NULL; } // initialise all pointer value to NULL
void add_element(int element) {
// Create a new Node
New = new ListElement;
New->set_element(element);
New->next = NULL;
// adding value or linkig each node to each other
(Start == NULL) ? Start = New : Tail->next = New;
Tail = New;
}
// print the whole linked list
void print()
{
ListElement* Current = Start;
while (Current != NULL)
{
cout << Current->get_value() << endl;
Current = Current->next;
}
}
};
Main Function
int main()
{
List L;
int num_of_element, element;
cin >> num_of_element;
for (int i(0); i < num_of_element; i++) {
cin >> element;
L.add_element(element);
}
L.print();
}
Hope it'll work.
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
I didn't put the full code because it was very long and i only need help with the small portion which is the **** area. i can't seem to use front() or top() to get the top element of the queue. I tried making top() function List keep getting error : 1) class List has no memeber named 'top' which means i don't have a function top in List, when i make it it says 2) no match for 'operator=' in printer_cpu[i] = SList::top() with T=PCB]()'
template <class T>
class node{
public:
T data;
node *next;
};
template <class T>
class List{
node<T> *head;
node<T> *tail;
public:
List()
{
head = tail = NULL;
}
bool isEmpty()
{
if(head == NULL) return true;
else return false;
}
void enqueue(T new_data){
node<T> *temp = new node<T>;
temp->data = new_data;
temp->next = NULL;
if(isEmpty()){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void dequeue(){
if(isEmpty())
{
cout << "The list is already empty" << endl;
}
node<T>* temp;
if(head == tail){
temp->data=head->data;
delete head;
head = tail = NULL;
}
else{
temp->data = head->data;
head = head->next;
delete temp;
}
}
node<T> top() // need help here ****
{
return head;
}
void display(){
node<T> *current = head;
while(current != NULL){
cout << current->data << endl;
current = current->next;
}
}
};
struct PCB
{
int ProcessID;
int ProcessorSize;
int priority;
string name;
};
typedef List<PCB> printing;
typedef List<PCB> disk;
void gen(vector<printing> &printer_queue,string printer_name[], int printers)
{
for(int i = 0; i < printers; i++)
{
int num = i+1;
ostringstream convert;
convert << num;
printer_name[i] = "p" + convert.str();
printer_queue.push_back(printing());
}
int main()
{
int numOfPrinter = 5;
string interrupt;
cin >> interrupt;
PCB cpu;
PCB printer_cpu[numOfPrinter];
string printer_name[numOfPrinter];
vector<printing> PQ;
gen(PQ,printer_name,numOfPrinter);
for(int i = 0; i < numOfPrinter; i++)
{
if(interrupt == printer_name[i])
{
cout << "Enter a name for this printer file: " << endl;
cin >> cpu.name;
PQ[i].enqueue(cpu);
printer_cpu[i] = PQ[i].top(); //need help here ****
}
}
}
It looks like you're missing an asterisk, because you need to return of type pointer, because that's what head is.
You should have
node<T> * top()
{
...
}
You also need to overload the = operator, because you are trying to compare type PCB with type node *.
Well, I compile your code successfully after correcting some mistakes.
I didn't meet class List has no memeber named 'top' problem.
Then your top() function returns the value of head, so you should change it to: node<T>* top() because head is a pointer to node<T>.
And the reason you got no match for 'operator=' error is that printer_cpu[i]'s type is PCB while PQ[i].top()'s type should be node<T>*
I have also found that the code you post lacks a } just before int main().
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;
}