Sorted queue linked list c++ - c++

I need to make a queue linked list in which the first node always has the smallest value , so it needs to be sorted , I have written this code :
#include <iostream>
using namespace std;
struct Node
{
int key;
Node *link;
};
class qlinkedlist
{
private:
Node *head;
Node *tail;
Node *curr;
Node *prev;
int count;
public:
void Enqueue(int value)
{
Node *newnode = new Node;
newnode -> key = value;
newnode -> link = NULL;
if(head==NULL)
{
head=tail=newnode;
count++;
}
else if(newnode->key < head->key)
{
newnode -> link = head;
head = newnode;
count++;
}
else
{
prev=head;
curr=head->link;
while(curr != NULL)
{
if(newnode->key < curr->key)
{
prev->link = newnode;
newnode->link = curr;
count++;
}
else
{
prev = curr;
curr = curr ->link;
}
}
}
}
void Dequeue()
{
if(head==NULL)
{
cout<< "Queue is empty" << endl;
}
else
{
curr = head;
head = head -> link;
delete curr;
count--;
}
}
void print()
{
curr = head;
while (curr!=NULL)
{
cout << curr -> key << endl;
curr = curr -> link;
}
}
};
void main()
{
qlinkedlist obj;
obj.Enqueue(5);
obj.Enqueue(4);
obj.Enqueue(3);
obj.Enqueue(2);
obj.Enqueue(1);
obj.print();
}
problem is it works only if I add nodes in the above order , for example if I try to add the 3 then 2 then 5 it does not work , what's wrong with the code ?
Thank you

Because if you try to add an element that is bigger than everything you have in the list, it will never pass your only condition to add a node: if(newnode->key < curr->key). Try this instead:
while(curr != NULL && newnode->key > curr->key)
{
prev = curr;
curr = curr ->link;
}
prev->link = newnode;
newnode->link = curr;
count++;
This way, you go through the linked list until you find the right spot, then add the new node even if you get to the end (curr==NULL).

Related

Segmentation fault in Linked List code, deletion part

I am trying to code for insertion and deletion in linked list.
Here is my code for basic insertion and deletion of nodes in a singly linked list.
There are no errors in the code, but the output on the terminal shows segmentation fault. Can someone explain why am I getting a segmentation fault? And what changes do i make to remove the fault.
I believe the segmentation fault is in the deletion part. Please help.
// class is a type of user defined datatype
class Node {
public:
int data;
Node* next;
//constructor
Node(int data) {
this -> data = data;
this -> next = NULL;
}
// destructor
~Node() {
int value = this -> data;
//memory free krr rhe hain
if(this -> next != NULL){
delete next;
this -> next = NULL;
}
cout << "memory is free for node with data" << value << endl;
}
};
void insertAtHead(Node* &head, int data) {
// creating new node called temp of type Node
Node* temp = new Node(data);
temp -> next = head;
head = temp;
}
void insertAtTail(Node* &head, Node* &tail, int data) {
// //New node create
// Node* temp = new Node(data);
// tail -> next = temp;
// tail = temp;
Node* temp = new Node(data);
if (head == nullptr) { // If this is the first node of the list
head = temp;
} else { // Only when there is already a tail node
tail -> next = temp;
}
tail = temp;
}
void insertAtPosition(Node* &tail, Node* &head, int position, int data) {
// Insert at starting
if(position == 1) {
insertAtHead(head, data);
return;
}
// Code for inserting in middle
Node* temp = head;
int cnt = 1;
while(cnt < position-1) {
temp = temp -> next;
cnt++;
}
// Creating a node for data
Node* nodeToInsert = new Node(data);
nodeToInsert -> next = temp -> next;
temp -> next = nodeToInsert;
// Inserting at last position (tail)
if(temp -> next == NULL) {
insertAtTail(head,tail, data);
return;
}
}
void deleteNode(int position, Node* &head) {
//deleting first or starting node
if(position == 1) {
Node* temp = head;
head = head -> next;
//memory free start node
temp -> next = NULL;
delete temp;
} else {
// deleting any middle node
Node* curr = head;
Node* prev = NULL;
int cnt = 1;
while(cnt <= position) {
prev = curr;
curr = curr -> next;
cnt++;
}
prev -> next = curr -> next;
curr -> next = NULL;
delete curr;
}
}
void print(Node* &head) {
Node* temp = head;
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
cout << endl;
}
int main() {
Node* head = nullptr; // A list has a head
Node* tail = head; // a tail.
insertAtHead(head, 10); // pass the head
insertAtTail(head, tail, 20);
insertAtTail(head, tail, 30);
insertAtHead(head, 5);
print(head); // Print the whole list
cout << "head" << head -> data << endl;
cout << "tail" << tail -> data << endl;
deleteNode(1, head);
print(head);
}
The problem is not with the delete function since even commenting it out leads to segmentation fault.
The problem is that you are initializing tail = head which is set to nullptr at the start. However, when you insertAtHead, you set the value of head but leave the tail to nullptr. You need to do tail = head when adding the first node (when head == nullptr).
Refer below for working code:
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
// class is a type of user defined datatype
class Node {
public:
int data;
Node* next;
//constructor
Node(int data) {
this -> data = data;
this -> next = NULL;
}
// destructor
~Node() {
int value = this -> data;
//memory free krr rhe hain
if(this -> next != NULL){
delete next;
this -> next = NULL;
}
cout << "memory is free for node with data" << value << endl;
}
};
void insertAtHead(Node* &head,Node* &tail, int data) {
// creating new node called temp of type Node
Node* temp = new Node(data);
temp -> next = head;
if (head == nullptr)
tail = temp; //inializing tail
head = temp;
}
void insertAtTail(Node* &head, Node* &tail, int data) {
// //New node create
// Node* temp = new Node(data);
// tail -> next = temp;
// tail = temp;
Node* temp = new Node(data);
if (head == nullptr) { // If this is the first node of the list
head = temp;
} else { // Only when there is already a tail node
tail -> next = temp;
}
tail = temp;
}
void insertAtPosition(Node* &tail, Node* &head, int position, int data) {
// Insert at starting
if(position == 1) {
insertAtHead(head,tail, data);
return;
}
// Code for inserting in middle
Node* temp = head;
int cnt = 1;
while(cnt < position-1) {
temp = temp -> next;
cnt++;
}
// Creating a node for data
Node* nodeToInsert = new Node(data);
nodeToInsert -> next = temp -> next;
temp -> next = nodeToInsert;
// Inserting at last position (tail)
if(temp -> next == NULL) {
insertAtTail(head,tail, data);
return;
}
}
void deleteNode(int position, Node* &head) {
//deleting first or starting node
if(position == 1) {
Node* temp = head;
head = head -> next;
//memory free start node
temp -> next = NULL;
delete temp;
} else {
// deleting any middle node
Node* curr = head;
Node* prev = NULL;
int cnt = 1;
while(cnt <= position) {
prev = curr;
curr = curr -> next;
cnt++;
}
prev -> next = curr -> next;
curr -> next = NULL;
delete curr;
}
}
void print(Node* &head) {
Node* temp = head;
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
cout << endl;
}
int main() {
Node* head = nullptr; // A list has a head
Node* tail = head; // a tail.
insertAtHead(head,tail, 10); // pass the head
insertAtTail(head, tail, 20);
insertAtTail(head, tail, 30);
insertAtHead(head,tail, 5);
print(head); // Print the whole list
cout << "head" << head -> data << endl;
cout << "tail" << tail -> data << endl;
deleteNode(1, head);
print(head);
}
The segfault is actually in the function insertAtTail(), and is because, while you handle the case where head is a null pointer, you do not handle the case where there is a head node but no tail node. The following code fixes this issue:
void insertAtTail(Node* &head, Node* &tail, int data) {
// //New node create
Node* temp = new Node(data);
if (head == nullptr) { // If this is the first node of the list
head = temp;
} else if (tail == nullptr) { // if there's a head but no tail
head -> next = temp;
} else { // Only when there is already a tail node
tail -> next = temp;
}
tail = temp;
}
If you have a look at this part of your code:
int main()
{
Node* head = nullptr; // A list has a head
Node* tail = head; // a tail.
insertAtHead(head, 10); // pass the head
insertAtTail(head, tail, 20);
return 0;
}
tail is a nullptr as you pass it into insertAtTail(head, tail, 20);
Then in insertAtTail you are going to access this nullptr:
void insertAtTail(Node* &head, Node* &tail, int data) {
// //New node create
// Node* temp = new Node(data);
// tail -> next = temp;
// tail = temp;
Node* temp = new Node(data);
if (head == nullptr) {
head = temp;
} else {
// here you have nullptr access resulting in your segmentation fault
tail -> next = temp;
}
tail = temp;
}

Linked List insertion isn't working in for/while loop

I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.
#include <iostream>
class Node {
public:
int data;
Node *next;
Node(int &num) {
this->data = num;
next = NULL;
}
};
class LinkedList {
Node *head = NULL;
public:
void insert(int num) {
Node *tmp;
if (head == NULL) {
head = new Node(num);
tmp = head;
} else {
tmp->next = new Node(num);
tmp = tmp->next;
}
}
void printList() {
Node *tmp = head;
while (tmp) {
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList() {
Node *curr = head, *prev = NULL, *nextNode;
while (curr) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main() {
LinkedList list1;
// This is not working
int num;
while (num != -1) {
std::cin >> num;
list1.insert(num);
}
// This is working
// list1.insert(1);
// list1.insert(2);
// list1.insert(3);
// list1.insert(4);
// list1.insert(5);
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}
I expect this after insertion
Edit:
although #Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?
for (int i = 1; i <= 10; i++)
{
list1.insert(i);
}
When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. This way you are only assigning to some *tmp then going out of scope loses all your data... The best way is to just keep a pointer to the last inserted item, no need to use *tmp.
class LinkedList
{
Node *head = NULL;
Node *tail = NULL;
public:
void insert(int num)
{
if (head == NULL)
{
head = new Node(num);
tail = head;
}
else
{
tail->next = new Node(num);
tail = tail->next;
}
}
...
}
You need to loop until you reach the end of the list and then add the new node after that. Like this.
void insert(int num) {
Node *tmp = head;
if (head == NULL) {
head = new Node(num);
}
else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new Node(num);
}
}
first of all you need to define a node for each of the tail and head of the list as follows
Node *h;
Node *t;
you may also separate the Node from the LinkedList class so you can modify easily
class Node{
public:
int data;
Node *next;
Node(int data, Node* next);
~Node();
};
Node::Node(int data, Node* next)
{
this->data= data;
this->next= next;
}
Node::~Node(){}
}
after that you can try to add these functions to your LinkedList class
so it can deal with other special cases such empty list or full, etc..
void addToHead(int data){
Node *x = new Node(data,h);
h=x;
if(t==NULL){
t=x;
}
void addToTail(int data){
Node *x = new Node(data,NULL);
if(isEmpty()){
h=t=x;
}
else
{
t->next=x;
t=x;
}
}
now for the insert function try this after you implemented the Node class and the other functions,
void insert(int v){
if(h==nullptr){addToHead(v); return;}
if(h->data>=v) {addToHead(v);return;}
if(t->data<=v) {addToTail(v); return;}
// In this case there is at least two nodes
Node *k=h->next;
Node *p=h;
while(k != nullptr){
if(k->data >v){
Node *z =new Node(v,k);
p->next=z;
return;
}
p=k;
k=k->next;
}
}
the idea of making all of this is not lose the pointer when it goes through elements in the Linked List so you don't end up with a run time error.
I hope this can be useful to you.
There was an issue with your insert function.
Read about segmentation fault here https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/#:~:text=Core%20Dump%2FSegmentation%20fault%20is,is%20known%20as%20core%20dump.
for a quick workaround you can use this
using namespace std;
#include <iostream>
class Node
{
public:
int data;
Node *next;
Node(int num)
{
this->data = num;
next = NULL;
}
};
class LinkedList
{
Node *head = NULL;
public:
void insert(int num)
{
Node *tmp= new Node(num);
tmp->next=head;
head=tmp;
}
void printList()
{
Node *tmp = head;
while (tmp)
{
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList()
{
Node *curr = head, *prev = NULL, *nextNode;
while (curr)
{
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main()
{
LinkedList list1;
// This is not working
int num,i=0,n;
cout<<"Type the value of n";
cin>>n;
while (i<n)
{
cin >> num;
cout<<num<<" "<<&num<<endl;
list1.insert(num);
i++;
}
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}

How to use point to next node when deleting elements in C++

I have previously posted some part of this task here.
I am now implementing a method that removes an element at a given index. My code is
void remove(int index)
{
if (head != NULL)
{
Node *current = get_node(index);
Node *prev = get_node(index - 1);
Node *next = get_node(index + 1);
prev->next = current->next;
delete current;
}
}
however, I am facing this error message
libc++abi.dylib: terminating with uncaught exception of type
std::range_error: IndexError: Index out of range
Abort trap: 6
I am guessing the problem is the pointers, but I am not sure why this is not working. Anyone who can help?
I think you can handle corner cases like this:
#include <iostream>
using namespace std;
struct Node {
Node(int val) {
this->val = val;
}
struct Node * next;
int val;
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = new Node(1);
Node * n1 = new Node(2);
head->next = n1;
Node * n2 = new Node(3);
n1->next = n2;
}
void remove(int index) {
if (head == NULL) {
return;
}
int pos = 0;
Node * cur = head;
Node *prev = NULL;
while (cur != NULL) {
if (pos == index) {
break;
}
pos++;
prev = cur;
cur = cur->next;
}
if (prev == NULL) {
head = head->next;
}
else {
prev->next = cur->next;
}
delete cur;
}
};
void print(Node * head){
cout << "Current linked list:\n";
while(head != NULL) {
cout << head->val << endl;
head = head->next;
}
cout << endl;
}
int main() {
LinkedList * list = new LinkedList();
print(list->head);
list->remove(0);
print(list->head);
list->remove(1);
print(list->head);
list->remove(0);
print(list->head);
}

Why is this if statement triggered in this C++ code?

This code is supposed to reverse a linked list. The following code returns an empty linked list even when provided with a non empty list.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* curr, *prev, *next;
if (head == NULL)
{
return head;
}
curr = head;
prev = NULL;
while (curr != NULL)
{
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
};
While this code strangely works where I added a cout statement just to check if the else was triggered.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* curr, *prev, *next;
if (head == NULL)
{
cout << "Triggered";
return head;
}
curr = head;
prev = NULL;
while (curr != NULL)
{
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
};
Can someone please explain why this is happening?
Pretty simple, you have to initialize the pointers, else it leads to unexpected behavior that includes not showing it at all or just showing it if an initialized cout is triggered - but it doesn't have to do anything and that's up to your compiler implementation.
//cpp17
listNode* curr{}, *prev{}, *next{};
//before
listNode* curr = nullptr, *prev = nullptr, *next = nullptr;
It is still not in the reverse order as you intended to do.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
listNode* curr{}, *prev{}, *next{};
//ListNode* curr, *prev, *next;
if (head == NULL)
{
return head;
}
curr = head;
prev = NULL;
while (next != NULL)
{
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
};
cheers :)
Like mentioned before I found time to write a solution for an other approach of solving your problem to reverse a linked list via class. For a better understanding for beginners I skipped the rule of three/five and initialized the list in the main function and not via constructor in the class:
#include <iostream>
class listElement
{
std::string data;
listElement* next;
listElement* last;
public:
void setData(std::string);
void append(std::string);
void displayElements();
void reverseDisplayElements(listElement*);
void freeMemory();
listElement* reverseList(listElement*);
};
void listElement::setData(std::string newData)
{
last = this;
data = newData;
next = nullptr;
}
void listElement::append(std::string newData)
{
// Double linked list
// last->next = new listElement();
// last->next->data = newData;
// last->next->next = nullptr;
// last = last->next;
// Singly linked list
//has next the value nullptr?
//If yes, next pointer
if (next == nullptr)
{
next = new listElement();
next->data = newData;
next->next = nullptr;
}
//else the method again
else
next->append(newData);
}
listElement* listElement::reverseList(listElement* head)
{
//return if no element in list
if(head == nullptr)
return nullptr;
//initialize temp
listElement* temp{};
while(head != nullptr){
listElement* next = head->next;
head->next = temp;
temp = head;
head = next;
}
return temp;
}
void listElement::displayElements()
{
//cout the first entry
std::cout << data << std::endl;
//if the end is not reached, call method next again
if (next != nullptr)
next->displayElements();
}
void listElement::reverseDisplayElements(listElement*head)
{
//recursiv from the last to the list beginning - stop
listElement *temp = head;
if(temp != nullptr)
{
if(temp->next != nullptr)
{
reverseDisplayElements(temp->next);
}
std::cout << temp->data << std::endl;
}
}
void listElement::freeMemory()
{
//If the end is not reached, call the method again
if (next != nullptr)
{
next->freeMemory();
delete(next);
}
}
int main ()
{
//Pointer to the Beginning of the list
listElement* linkedList;
//Creating the first element
linkedList = new listElement();
//Write data in the first element
linkedList->setData("Element 1");
//add more elements
linkedList->append("Element 2");
linkedList->append("Element 3");
linkedList->append("Element 4");
//display list
linkedList->displayElements();
//space divider
std::cout << "\nPrint in reverse order:" << std::endl;
//display list in reverse order
//pass list beginning as stop point
linkedList->reverseDisplayElements(linkedList);
std::cout << std::endl;
linkedList->displayElements();
std::cout << "\nReverse elements:" << std::endl;
linkedList = linkedList->reverseList(linkedList);
linkedList->displayElements();
std::cout << std::endl;
//destruct the list and free memory
linkedList->freeMemory();
delete(linkedList);
return 0;
}
Btw. there are many different solutions for that task.

Moving first item in linked list to end C++

I need to move the first item in a linked list to the end of the list. My problem is I'm going in to an infinite loop. When I remove the cause for the infinite loop (tail -> link != NULL; in the for loop), I get a seg fault. So, looking for ideas on how to get this code to work.
#include <iostream>
#include <string>
using namespace std;
struct Node
{
string data;
Node *link;
};
class Lilist
{
public:
Lilist() {head = NULL;}
void add(string item);
void show();
void move_front_to_back();
Node* search(string target);
private:
Node *head;
};
int main()
{
Lilist L1, L2;
string target;
L1.add("Charlie"); //add puts a name at the end of the list
L1.add("Lisa");
L1.add("Drew");
L1.add("Derrick");
L1.add("AJ");
L1.add("Bojian");
cout << "Now showing list One:\n";
L1.show(); // displays the list (This function displayed the list properly)
cout << "\n";
L1.move_front_to_back();
L1.move_front_to_back();
L1.show();
cout << "\n";
return(0);
}
void Lilist::add(string item)
{
Node *temp;
if(head == NULL)
{
head = new Node;
head -> data = item;
head -> link = NULL;
}
else
{
for(temp = head; temp -> link != NULL; temp = temp -> link)
;
temp -> link = new Node;
temp = temp -> link;
temp -> data = item;
temp -> link = NULL;
}
}
void Lilist::show()
{
for(Node *temp = head; temp != NULL; temp = temp -> link)
std::cout << temp -> data << " ";
}
void Lilist::move_front_to_back()
{
Node *temp;
Node *tail;
temp = head;
for(tail = head; tail != NULL; tail = tail -> link)
;
head = head -> link;
tail -> link = temp;
temp -> link = NULL;
}
The problem is in how you compute tail. Notice this (unrelated lines omitted for brevity):
for(tail = head; tail != NULL; tail = tail -> link)
;
tail -> link = temp;
Notice that the for loop will only terminate once tail is NULL. Then, you dereference tail ... which is null.
So change the for loop condition:
for (tail = head; tail->link != NULL; tail = tail->link)
;
This will find the last element in the list, instead of flowing off the end.
[Live example]
Angew already explained why your original code was failing. I would suggest an alternative approach - give Lilist a tail member that is managed alongside its head member. Then you don't have to hunt for the tail whenever you need it, you always know exactly which Node is the current tail, eg:
#include <iostream>
#include <string>
using namespace std;
struct Node
{
string data;
Node *next;
Node(string s);
};
class Lilist
{
public:
Lilist();
~Lilist();
void add(string item);
void show();
void move_front_to_back();
Node* search(string target);
private:
Node *head;
Node *tail;
};
Node::Node(string s)
: data(s), next(NULL)
{
}
Lilist::Lilist()
: head(NULL), tail(NULL)
{
}
Lilist::~Lilist()
{
for(Node *temp = head; temp != NULL; temp = temp->next)
delete temp;
}
void Lilist::add(string item)
{
Node *temp = new Node(item);
if (head == NULL)
head = temp;
if (tail != NULL)
tail->next = temp;
tail = temp;
}
void Lilist::show()
{
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->data << " ";
}
void Lilist::move_front_to_back()
{
if (head == tail)
return;
Node *temp = head;
head = temp->next;
temp->next = NULL;
tail->next = temp;
tail = temp;
}
Node* Lilist::search(string target)
{
for(Node *temp = head; temp != NULL; temp = temp->next)
{
if (temp->data == target)
return temp;
}
return NULL;
}