// Online C compiler to run C program online
i have tried to create a linked list and print the elements but its not working.could you please help me
// Online C compiler to run C program online
#include <stdio.h>
#include <stdlib.h>
struct sai{
int data;//data that needs to be stored
struct sai *ptr;//self pointer
};
void printplaces();
int main(){
struct sai *head;
struct sai *second;
struct sai *third;
struct sai *fourth;
head = (struct sai*)malloc(sizeof(struct sai));
second = (struct sai*)malloc(sizeof(struct sai));
third = (struct sai*)malloc(sizeof(struct sai));
fourth = (struct sai*)malloc(sizeof(struct sai));
(*head).data = 2;
head->ptr = second;
(*second).data = 2;
second->data = third;
(*third).data = 2;
third->ptr = fourth;
(*fourth).data = 2;
fourth->ptr = '\0';
printplaces(*head);
/*printf("%d\n",(*head).ptr);
printf("%d\n",(*second).ptr);
printf("%d\n",(*third).ptr);
printf("%d\n",(*fourth).ptr);
printplaces(*head);
}*/
}
void printplaces(struct sai *next){
for(int i = 0; i<= 2; i++){
printf("%d", next->data);
next = next -> ptr;
}
}
this line is wrong
second->data = third;
you mean
second->ptr = third;
and all the other places where you are trying to set the 'next' pointer
also
(*head).data = 2;
is better written
head->data = 2;
so you need
head->data = 2;
head->ptr = second;
second->data = 2;
second->ptr = third;
third->data = 2;
third->ptr = fourth;
fourth->data = 2;
fourth->ptr = '\0';
Related
This is a programming assignment from university. The main program was given to me by the professor. I have to create the dlist.h. When I debug, I receive this segmentation error. I also have this:
get (dl=..., val=<error reading variable>) at dlist.h:37
#include <iostream>
#include <exception>
struct DListElem { //element of the list
int info;
DListElem * prev;
DListElem * next;
};
struct DList{ //just stores pointers to first and last elements of the list
DListElem * first;
DListElem * last;
};
void initializeDList(DList & dl){ //Iinitializes dl as empty list
dl.first = nullptr;
dl.last = nullptr;
}
void put(DList& dl, int val){ //insert a new element with value val at the beginning of the list.
DListElem* front_elem = new DListElem;
front_elem ->info = val;
front_elem -> prev = nullptr;
front_elem -> next = dl.first;
dl.first = front_elem;
if(dl.last==NULL) dl.last=dl.first;
}
bool get(DList& dl, int& val){
/*Removes an item (if possible) from the end of the list. The value of the last
element is returned by the val parameter, the memory for the list element
is released. The return value indicates whether an item could be retrieved,
i.e. it returns false for an empty list and true otherwise.*/
if(dl.last==nullptr) return false;
if (dl.first==dl.last){ //if there is only 1 element
val = dl.last -> info;
DListElem* buffer = new DListElem;
buffer = dl.last;
dl.last = nullptr;
dl.first = nullptr;
delete (buffer);
}
else{
val = dl.last -> info;
DListElem* buffer = new DListElem;
buffer = dl.last;
dl.last = dl.last -> prev;
dl.last -> next = nullptr; //this part seems to still be the problem
delete (buffer);
};
return true;
}
And this is my main program:
#include <iostream>
#include "dlist.h"
using namespace std;
int main (int argc, char *argv[]) {
DList queue;
initializeDList (queue);
inserts 5 values
for (int i = 1; i <= 5; i++) {
cout << "put: " << 10 * i << endl;
put (queue, 10 * i);
}
removes 3 values and prints them to console
for (int j = 1; j <= 3; j++){
int value;
if (get (queue, value))
cout << " get: " << value << endl;
}
I guess these are necessary:
cin.sync ();
cin.get ();
return 0;
}
okay, the issue was with the function put(); I didn't implement it well enough and it produced only a single linked list; consequently, dl.last became null in the function get() and the expression dl.last -> next = nullptr; was the reason for the problem;
this is the corrected put()
put (DList & dl, int val)
{ //insert a new element with value val at the beginning of the list.
DListElem *front_elem = new DListElem;
front_elem->info = val;
front_elem->prev = nullptr;
front_elem->next = dl.first;
if (dl.first != nullptr && dl.first->next == nullptr)
dl.last = dl.first;
if (dl.first != nullptr)
dl.first->prev = front_elem;
dl.first = front_elem;
}
I am using linked lists to simulate a computer lab, and I am trying to print the linked lists. There's an issue with printing using cout, it produces garbage until the terminal just gives up and sends a segmentation fault 11.
#include <iostream>
#include <string>
using namespace std;
struct lab {
string current_ID;
int station_number;
lab *link;
};
typedef lab* lab_ptr;
void print_status(lab_ptr& head1, lab_ptr& head2, lab_ptr& head3, lab_ptr& head4);
int main()
{
lab_ptr head_lab_1;
head_lab_1 = new lab;
lab_ptr head_lab_2;
head_lab_2 = new lab;
lab_ptr head_lab_3;
head_lab_3 = new lab;
lab_ptr head_lab_4;
head_lab_4 = new lab;
set_up_linked_list_for_n_stations(head_lab_1, 5);
set_up_linked_list_for_n_stations(head_lab_2, 6);
set_up_linked_list_for_n_stations(head_lab_3, 4);
set_up_linked_list_for_n_stations(head_lab_4, 3);
return 0;
}
void set_up_linked_list_for_n_stations(lab_ptr& head, int n)
{
lab_ptr curr;
curr = new lab;
for(int j = 0; j < n; j++)
{
lab_ptr temp = new lab;
temp->link = NULL;
temp->station_number = n+1;
temp->current_ID = 'empty';
cout << temp->station_number << " " << temp->current_ID << endl;
if(head != NULL)
{
curr = head;
while(curr->link != NULL)
{
curr = curr->link;
}
curr->link = temp;
} else
{
head = temp;
}
}
}
This is literally my first time using linked lists, so the error can be something incredibly obvious that i just missed. Sorry for advanced if it's a dumb mistake.
For the string member current_ID you need to pass the value using double quotes:
temp->current_ID = 'empty';
becomes
temp->current_ID = "empty";
Also you need to move the function void set_up_linked_list_for_n_stations(lab_ptr& head, int n) before the main()
You are making extra allocations, other place the list is not properly initialized. Initialize head_lab_1 to nullptr (or just NULL)
In the function set_up_linked_list_for_n_stations remove curr = new lab
void set_up_linked_list_for_n_stations(lab_ptr& head, int n)
{
for(int j = 0; j < n; j++)
{
lab_ptr temp = new lab;
temp->link = NULL;
temp->station_number = n + 1;
temp->current_ID = "empty";
cout << temp->station_number << " " << temp->current_ID << endl;
if(head != NULL)
{
lab_ptr curr = head;
while(curr->link != NULL)
{
curr = curr->link;
}
curr->link = temp;
}
else
{
head = temp;
}
}
}
int main()
{
lab_ptr head_lab_1 = nullptr;
lab_ptr head_lab_2 = nullptr;
lab_ptr head_lab_3 = nullptr;
lab_ptr head_lab_4 = nullptr;
set_up_linked_list_for_n_stations(head_lab_1, 5);
set_up_linked_list_for_n_stations(head_lab_2, 6);
set_up_linked_list_for_n_stations(head_lab_3, 4);
set_up_linked_list_for_n_stations(head_lab_4, 3);
return 0;
}
I have implemented a basic linked list in order to prepare for a more difficult one as an assignment. I can't seem to be able to print the contents of a node without printing out random symbols.
I know this means I am accessing bad memory but I cannot identify where or how it is happening.
Can someone please help me fix this error?
built with g++ on linux
Header File
#ifndef LLIST_H
#define LLIST_H
#include <string>
using namespace std;
struct node
{
int age;
string name;
string hair;
int height;
node* next;
};
node loadNode(node a, string b);
class linkedlist
{
private:
node* head = NULL;
node* tail = NULL;
int size;
public:
linkedlist();
linkedlist(node* n[], int si);
int getSize();
void print();
void addNode(node add);
void del(string record);
node sort(node sortee);
void printList();
node * getHead();
};
#endif
Implementation
#include "list.h"
#include <iostream>
#include <sstream>
#include <string>
node loadNode(node a, string b)
{
int counter = 0;
string ag = "";
string nam = "";
string hai = "";
string hei = "";
for(int i = 0; i < b.length(); i++)
{
if(b[i] == ',')
{
counter++;
i++;
}
if(counter == 0)
ag = ag + b[i];
else if(counter == 1)
nam = nam + b[i];
else if(counter == 2)
hai = hai + b[i];
else
hei = hei + b[i];
}
stringstream s(hei);
stringstream o(ag);
int f,g;
s >> f;
o >> g;
a.hair = hai;
a.height = f;
a.age = g;
a.name = nam;
return a;
}
linkedlist::linkedlist()
{
head = NULL;
tail = NULL;
size = 0;
}
linkedlist::linkedlist(node a[],int si)
{
head = NULL;
tail = NULL;
size = 0;
for(int i = 0; i < si; i++)
{
addNode(a[i]);
}
}
void linkedlist::addNode(node added)
{
node * pointer = new node;
//if the first element
if(size == 0)
{
tail = pointer;
pointer->next = NULL;
}
pointer->next = head;
head = pointer;
//add data members
pointer-> age = added.age;
pointer-> hair = added.hair;
pointer-> name = added.name;
pointer-> height = added.height;
size++;
//time to exit!
pointer = NULL;
delete pointer;
}
node * linkedlist::getHead()
{
node * temp = head;
return temp;
}
void linkedlist::print()
{
node* iterator = (node*)malloc(sizeof(node));
iterator = head;
while(iterator != NULL)
{
printNode(iterator);
iterator = (iterator->next);
}
iterator = NULL;
delete iterator;
}
void printNode(node* printed)
{
cout << printed->name << endl;
cout << printed->age << endl;
cout << printed->height << endl;
cout << printed->hair<< endl;
}
main program
#include "list.h"
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string k = "21,Ces Goose,brown,5";
string a = "25, SteveO, Brown, 6";
string b = "23, Jimmy , Brown, 5";
node d,f,c;
d = loadNode(d,k);
f = loadNode(f,a);
c = loadNode(c,b);
node lib[3] = {d,f,c};
linkedlist doublel = linkedlist(lib, 3);
doublel.print();
return 0;
}
The output I am getting is:
6304000
#g���
#C.M. please let me know if this fixes the issue
void linkedlist::addNode(node added)
{
node * temp = new node;
//add data members
temp-> age = added.age;
temp-> hair = added.hair;
temp-> name = added.name;
temp-> height = added.height;
//if the first element
if(size == 0)
{
head = temp;
tail = temp;
temp->next = NULL;
size++;
}
else
{
temp->next = head;
head = temp;
size++;
//time to exit!
temp = NULL;
delete pointer;
}
}
also changed linkedlist doublel = linkedlist(lib, 3); to
linkedlist * doublel = new linkedlist(lib,3);
doublel->print();
in main() file
i want to make a linked list ..
but the first node with a data and null link
if i input a string (123)
linked list be like this:
1/null - 2/point to the last one(1) - 3/point to the last one(2)
#include <iostream>
#include <string>
using namespace std;
struct link
{
int data;
link* next;
};
class LinkedList
{
private:
link* first;
public:
LinkedList(){}
void Add(string s)
{
for (int i = 0; i > s.length(); i++)
{
if (i == 0)
{
first->data = s[i];
first->next = NULL;
}
else
{
link* NewOne = new link;
NewOne->data = s[i];
NewOne->next = first;
first = NewOne;
}
}
}
void display()
{
cout << first->data;
}
};
int main()
{
LinkedList l1;
l1.Add("2734");
l1.display();
return 0;
}
what's the wrong in the code
You forget to allocate memory for first.
Following may help (using std::unique_ptr for free/correct memory management):
struct link{
char data;
std::unique_ptr<link> next;
};
class LinkedList {
private:
std::unique_ptr<link> first;
public:
void Set(const std::string& s){
for (auto c : s) {
std::unique_ptr<link> node = std::move(first);
first = std::make_unique<link>();
first->data = c;
first->next = std::move(node);
}
}
Live example
It also looks like you're storing characters in an int. Your output will be the ASCII value of the character rather than the raw int values.
I would recommend using unique pointers as Jarod42 has done. Having said that, this quick example below does not use them so you will need to call delete appropriately or use unique_ptr.
I added a last pointer to help traversal of the list as we make new links.
private:
Link * first;
Link *last;
int numLinks;
public:
LinkedList()
{
first = NULL;
last = NULL;
numLinks = 0;
}
Now for Add
void Add(string s)
{
for (int i = 0; i < s.length(); i++)
{
if (numLinks == 0)
{
first = new Link;
first->data = (s[i] - '0');
first->next = NULL;
last = first;
numLinks++;
}
else
{
Link * newLink = new Link;
newLink->data = (s[i] - '0');
newLink->next = NULL;
last->next = newLink;
last = newLink;
numLinks++;
}
}
}
The constructor does not initialize the first member. Subsequently, in Add():
for (int i = 0; i > s.length();i++){
if (i == 0){
first->data = s[i];
first->next = NULL;
}
This ends up dereferencing an uninitialized pointer, leading to undefined behavior.
There's also a problem with your display() too, but this is the main problem.
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node{
int size;
char* name;
node* next;
}node;
void insertnodes( node** arrayhead , int index , node* ptr){
index = index - 1 ;
while ( index--){
*arrayhead = (*arrayhead)->next;
}
(*arrayhead)->next = new node;
(*arrayhead)->next = ptr;
}
int main(){
int n = 4;
node *A[n] ;
for ( int i = 0 ; i < n ; i++){
A[i] = NULL ;
}
A[0] = new node;
A[0]->size = 10;
A[0]->name = new char;
A[0]->name = "gunna";
A[0]->next = NULL;
//cout << A[0]->name << endl;
node* ptr = new node ;
ptr->size = 10;
ptr->name = new char;
ptr->name = "param";
ptr->next = NULL;
insertnodes(&A[0] , 1 , ptr);
node* ptrr = new node ;
ptrr->size = 10;
ptrr->name = new char;
ptrr->name = "sidd";
ptrr->next = NULL;
insertnodes(&A[0] , 2 , ptrr);
cout << A[0]->name << endl;
cout << A[0]->next->name;
}
It should have to print "gunna" and "param" .
but it is giving "param" and "sidd" as output.
I don'nt know where i am going wrong . I have tried a lot of things but i am still confused
Pls help ...
I am using code blocks to compile this program ..
In your insertnodes() you are passing a double pointer node** arrayhead, thus, by dereferncing it later, you are overwriting the current value of next pointer, which will later cause memory leak in your program.
What you should do instead is create a temporary variable node* tmp which you will change when the index decreases. Then, you don't need to allocate a new node to the next pointer, because you already have a pointer you want to attach as next.
The fixed code would look like this:
void insertnodes(node** arrayhead, int index, node* ptr) {
index = index - 1;
node* tmp = *arrayhead;
while (index--) {
tmp = tmp->next;
}
tmp->next = ptr;
}
EDIT: This is completely useless:
int n = 4;
node *A[n] ;
for ( int i = 0 ; i < n ; i++){
A[i] = NULL ;
}
All you need to create a linked list is a single node (e.g. list's head).
But as this is a linked list, you don't need to pass index really. All you need is a head, over which you could iterate until you find node->next which will be NULL - this is the place you need to insert your new node at (this is how it's typically done).