Custom implementation of doubly linked list not working (educational) - c++

I implemented my own simple version of a doubly linked list. Unfortunately, there seems to be an error with it. The head of the list seems to move to the new Node, each time I add one with push_back. Because of this, print will print the last value indefinitely.
Linked List:
struct doubly_linked_list
{
Node *head = nullptr;
Node *tail = nullptr;
void push_back(Node n)
{
if (this->head == nullptr)
{
this->head = &n;
this->tail = nullptr;
}
n.prev = this->tail;
if (this->tail)
{
n.prev->next = &n;
}
this->tail = &n;
}
void print()
{
Node *tmp = this->head;
while (tmp != nullptr)
{
std::cout << tmp->data << ", ";
tmp = tmp->next;
}
}
};
Where Node is implemented as
struct Node
{
int data;
Node *next = nullptr;
Node *prev = nullptr;
Node(int data)
{
this->data = data;
}
Node()
{
this->data = -1;
}
};
main
int main()
{
doubly_linked_list dl;
dl.push_back(Node{3});
dl.push_back(Node{2});
dl.push_back(Node{1});
dl.push_back(Node{0});
dl.push_back(Node{5});
dl.print(); // print 5 forever
}
Disclaimer: Pls be aware that the topic of this post is educational. I know about the lists in the c++ standard.

Here is a working example with raw pointers, deppending on what you are doing you might want to change that to smart pointers.
#include <iostream>
struct Node
{
int data;
Node *next = nullptr;
Node *prev = nullptr;
Node(int data)
{
this->data = data;
}
Node()
{
this->data = -1;
}
};
struct doubly_linked_list
{
Node *head = nullptr;
Node *tail = nullptr;
void push_back(Node* n)
{
if (this->head == nullptr)
{
this->head = n;
this->tail = nullptr;
}
n->prev = this->tail;
if (this->tail)
{
n->prev->next = n;
}
this->tail = n;
}
void print()
{
Node *tmp = this->head;
while (tmp != nullptr)
{
std::cout << tmp->data << ", ";
tmp = tmp->next;
}
}
};
int main()
{
doubly_linked_list dl;
dl.push_back(new Node{3});
dl.push_back(new Node{2});
dl.push_back(new Node{1});
dl.push_back(new Node{0});
dl.push_back(new Node{5});
dl.print(); // print 5 forever
}

Related

Number of element inside linked list

I want to save the number of element inside an instance of linked list class object. From the code below everytime I call addNodeFront() or addNodeBack() function, member variable len should be incremented by 1. But, when I run the code, the getLen function only return 1, while the linked list has 2 element. What should I fix from the my code?
#include <iostream>
class Node {
public:
int value;
Node* next;
Node(int value, Node* next) {
this->value = value;
this->next = next;
}
};
class LinkedList {
public:
Node* head;
Node* tail;
int len = 0;
LinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
LinkedList(Node* node) {
this->head = node;
this->tail = node;
}
int getLen() {
return len;
}
void addNodeFront(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
Node* secondFirst = this->head;
this->head = node;
node->next = secondFirst;
this->len++;
}
void addNodeBack(Node* node) {
if(head==nullptr && tail==nullptr) {
this->head = node;
this->tail = node;
return;
}
this->tail->next = node;
this->tail = node;
this->len++;
}
void addNodeAfterNode(Node* prevNode, Node* node) {
if(prevNode == this->tail) {
this->tail = node;
prevNode->next = node;
return;
}
node->next = prevNode->next;
prevNode->next = node;
}
bool searchVal(int val) const {
Node* s = this->head;
while(s != nullptr) {
if(s->value == val) return true;
s = s->next;
}
return false;
}
void deleteNodeFront() {
if(this->head==this->tail) {
this->head = nullptr;
this->tail = nullptr;
return;
}
this->head = this->head->next;
}
void deleteNodeBack() {
Node* secondLast = this->head;
if(this->head==this->tail) {
this->head = nullptr;
this->tail = nullptr;
return;
}
while(secondLast->next != this->tail) {
secondLast = secondLast->next;
}
secondLast->next = nullptr;
this->tail = secondLast;
}
void deleteNodeMiddle(Node* node) {
if(node==this->head || node==this->tail) return;
Node* prevNode = this->head;
while(prevNode->next != node) {
prevNode = prevNode->next;
}
prevNode->next = prevNode->next->next;
}
void traverseLinkedList() {
Node* t = this->head;
if(head==nullptr && tail==nullptr) std::cout << "Empty Linked List";
while(t != nullptr) {
std::cout << t->value << "->";
t = t->next;
}
std::cout << "\n";
}
};
int main() {
Node node1(2,nullptr);
Node node4(4,nullptr);
LinkedList ls;
ls.addNodeFront(&node1);
ls.addNodeFront(&node4);
std::cout << ls.getLen() << std::endl;
ls.traverseLinkedList();
}
In the following function:
LinkedList(Node* node)
{
this->head = node;
this->tail = node;
}
Just add one of the following lines:
len++; //1
len = 1; //2
So the updated function:
LinkedList(Node* node)
{
this->head = node;
this->tail = node;
len++; //1
len = 1; //2
}
This is because as the head node and the tail node = node now, that means there is a node in the linked list, so we should add 1 to len.

Linked list c++ insertback

I am really new to data structures. I am trying to figure out why my insertback() function doesn't work. The first print does 3,2,1 but the second doesn't print anything. I think it has something to do with head, but I'm not really sure. Please help.
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
class lst
{
public:
void Insertfron(int x);
void Print();
void Insertback(int x);
private:
Node* head;
};
void lst::Insertfron(int x)
{
Node* temp = new Node;
temp->data = x;
temp->next = head;
head = temp;
}
void lst::Print()
{
Node* temp = head;
while(temp->next!=NULL)
{
cout<<temp->data<<' ';
temp=temp->next;
}
cout<< endl;
}
void lst::Insertback(int x)
{
Node* backinst = new Node;
backinst->data = x;
backinst->next = NULL;
Node* temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = backinst;
}
int main()
{
lst listt;
listt.Insertfron(1);
listt.Insertfron(2);
listt.Insertfron(3);
listt.Print();
listt.Insertback(4);
listt.Print();
return 0;
}
You are not initializing head to NULL to indicate an empty list, so ``head` will have a random garbage value, and thus all of your methods exhibit undefined behavior.
Once that is fixed, your while loops in both Print() and Insertback() are buggy, as they are not account for head being NULL when the list is empty.
Also, you are leaking every node you create. You need to add a destructor to free the nodes when you are done using the list.
With that said, try something more like this instead:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
class lst
{
public:
lst();
~lst();
void Insertfron(int x);
void Print();
void Insertback(int x);
private:
Node* head;
};
lst::lst()
: head(NULL)
{
}
lst::~lst()
{
while (head != NULL)
{
Node *next = head->next;
delete head;
head = next;
}
}
void lst::Insertfron(int x)
{
Node* temp = new Node;
temp->data = x;
temp->next = head;
head = temp;
}
void lst::Print()
{
Node* temp = head;
while (temp != NULL)
{
cout << temp->data << ' ';
temp = temp->next;
}
cout << endl;
}
void lst::Insertback(int x)
{
Node* backinst = new Node;
backinst->data = x;
backinst->next = NULL;
if (head == NULL)
{
head = backinst;
}
else
{
Node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = backinst;
}
}
int main()
{
lst listt;
listt.Insertfron(1);
listt.Insertfron(2);
listt.Insertfron(3);
listt.Print();
listt.Insertback(4);
listt.Print();
return 0;
}
That being said, Insertback() can be simplified to avoid the extra if by using an extra level of pointer indirection:
void lst::Insertback(int x)
{
Node **temp = &head;
while (*temp != NULL)
{
temp = &((*temp)->next);
}
Node* backinst = new Node;
backinst->data = x;
backinst->next = NULL;
*temp = backinst;
}

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;
}

SIGSEGV (Segmentation fault) c++ at fuction for pushBack() of list

I catched segfault when run this code and can`t understand why.
If firstly i use one time push(&head,3); then segfault is not catched, but it works bad for true
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void push(Node **head,int data)
{
Node *tmp = new Node;
tmp->data = data;
tmp->next = (*head);
(*head) = tmp;
}
Node *getLast(Node *head)
{
if(head == nullptr)
{
return nullptr;
}
while(head->next)
{
head=head->next;
}
return head;
}
void show(const Node *head)
{
while(head!=nullptr)
{
cout << head->data << endl;
head = head->next;
}
}
void pushBack(Node *head,int data)
{
Node *last = getLast(head);
Node *tmp = new Node;
tmp->data = data;
tmp->next = nullptr;
last->next = tmp;
}
int main() {
Node *head=nullptr;
**//push(&head,2); /////if I use this then it works! but it not right.**
pushBack(head,10);
pushBack(head,2);
pushBack(head,3);
show(head);
return 0;
}
I tried to google it but it helpless.
How to solve this problem?
If the linked list is empty you have to modify head which requires to pass the reference of head. This should work:
void pushBack(Node **head,int data)
{
Node *last = getLast(*head);
Node *tmp = new Node;
tmp->data = data;
tmp->next = nullptr;
if(last == nullptr)
{
*head = tmp;
}
else
{
last->next = tmp;
}
}
int main() {
Node *head=nullptr;
pushBack(&head,10);
pushBack(&head,2);
pushBack(&head,3);
show(head);
return 0;
}

A normal Linked List

I decided to practice my linked-list knowledge, and decided to create one in C++!
I ran this code on two different online compilers - one worked, and the other is giving me a segfault. I cannot figure out what the problem is within my code, and am wondering if you can help me.
#include <iostream>
using namespace std;
struct Node {
int val;
Node *next;
Node(int val){
this->val = val;
this->next = NULL;
}
};
class LinkedList {
public:
Node *head;
void insertAtHead(Node *temp)
{
if (head == NULL)
{
head = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void printList()
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->val << endl;
temp = temp->next;
}
}
void insertAtBack(Node *temp)
{
if (head == NULL)
{
head = temp;
return;
}
Node *current = head;
while (current->next != NULL){
current = current->next;
}
current->next = temp;
}
void deleteNode(Node *temp)
{
if (head == NULL)
{
cout << "Empty List";
return;
}
if (head->val == temp->val)
{
head = head->next;
return;
}
Node *current = head;
while (current->next != NULL)
{
if (current->next->val == temp->val)
{
current->next = current->next->next;
return;
}
current = current->next;
}
}
};
int main()
{
Node *temp = new Node(10);
Node *temp2 = new Node(4);
Node *temp3 = new Node(17);
Node *temp4 = new Node(22);
Node *temp5 = new Node(1);
LinkedList x;
x.insertAtHead(temp);
x.insertAtHead(temp2);
x.insertAtBack(temp3);
// x.insertAtBack(temp4);
// x.insertAtBack(temp5);
// x.deleteNode(temp);
x.printList();
return 0;
}
The problem I am encountering is when I use the insertAtBack() method. It gives me a segfault, but I do not see what's wrong with the logic. It is pretty straight forward. The insertAtFront() method works, but once I call insertAtBack() my code fails.
make sure to initialize Node *head to NULL.
After insert temp(which is value 10), temp->next value becomes undefined value, because Node *head is undefined value.
Your LinkedList class is not initializing its head member. You need to add a constructor to initialize head to NULL.
Also, the class is leaking memory, as there is no destructor to free the nodes when a LinkedList instance is destroyed, and deleteNode() doesn't free the node being removed, either.
Try something more like this:
#include <iostream>
using namespace std;
struct Node
{
int val;
Node *next;
Node(int val) : val(val), next(NULL) { }
};
class LinkedList
{
private:
Node *head;
// if you are NOT using C++11 or later, add these
// until you are reading to tackle copy semantics!
/*
LinkedList(const LinkedList &);
LinkedList& operator=(const LinkedList &);
*/
public:
LinkedList() : head(NULL) {} // <-- add this!
~LinkedList() // <-- add this!
{
Node *current = head;
while (current)
{
Node *next = current->next;
delete current;
current = next;
}
}
void insertAtHead(Node *temp)
{
if (!head)
{
head = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void printList()
{
Node *current = head;
while (current)
{
cout << current->val << endl;
current = current->next;
}
}
void insertAtBack(Node *temp)
{
if (!head)
{
head = temp;
return;
}
Node *current = head;
while (current->next) {
current = current->next;
}
current->next = temp;
}
void deleteNode(Node *temp)
{
if (!head)
{
cout << "Empty List";
return;
}
if (head == temp)
{
head = temp->next;
delete temp;
return;
}
Node *current = head;
while (current->next)
{
if (current->next == temp)
{
current->next = temp->next;
delete temp;
return;
}
current = current->next;
}
}
// if you ARE using C++11 or later, add these until
// you are reading to tackle copy and move semantics!
/*
LinkedList(const LinkedList &) = delete;
LinkedList(LinkedList &&) = delete;
LinkedList& operator=(const LinkedList &) = delete;
LinkedList& operator=(LinkedList &&) = delete;
*/
};
int main()
{
Node *temp = new Node(10);
Node *temp2 = new Node(4);
Node *temp3 = new Node(17);
Node *temp4 = new Node(22);
Node *temp5 = new Node(1);
LinkedList x;
x.insertAtHead(temp);
x.insertAtHead(temp2);
x.insertAtBack(temp3);
// x.insertAtBack(temp4);
// x.insertAtBack(temp5);
// x.deleteNode(temp);
x.printList();
return 0;
}
Which can then be simplified further:
#include <iostream>
using namespace std;
struct Node
{
int val;
Node *next;
Node(int val, Node *next = NULL) : val(val), next(next) { }
};
class LinkedList
{
private:
Node *head;
// if you are NOT using C++11 or later, add these
// until you are reading to tackle copy semantics!
/*
LinkedList(const LinkedList &);
LinkedList& operator=(const LinkedList &);
*/
public:
LinkedList() : head(NULL) {} // <-- add this!
~LinkedList() // <-- add this!
{
Node *current = head;
while (current)
{
Node *next = current->next;
delete current;
current = next;
}
}
Node* insertAtHead(int value)
{
Node *temp = new Node(value, head);
if (!head)
head = temp;
return temp;
}
void printList()
{
Node *current = head;
while (current)
{
cout << current->val << endl;
current = current->next;
}
}
Node* insertAtBack(int value)
{
Node **current = &head;
while (*current)
current = &((*current)->next);
*current = new Node(value);
return *current;
}
/*
void deleteNode(Node *temp)
{
Node *current = head, *previous = NULL;
while (current)
{
if (current == temp)
{
if (previous)
previous->next = temp->next;
if (head == temp)
head = temp->next;
delete temp;
return true;
}
previous = current;
current = current->next;
}
cout << "Not found" << endl;
return false;
}
*/
bool deleteValue(int value)
{
Node *current = head, *previous = NULL;
while (current)
{
if (current->val == value)
{
if (previous)
previous->next = temp->next;
if (head == temp)
head = temp->next;
delete temp;
return true;
}
previous = current;
current = current->next;
}
cout << "Not found" << endl;
return false;
}
// if you ARE using C++11 or later, add these until
// you are reading to tackle copy and move semantics!
/*
LinkedList(const LinkedList &) = delete;
LinkedList(LinkedList &&) = delete;
LinkedList& operator=(const LinkedList &) = delete;
LinkedList& operator=(LinkedList &&) = delete;
*/
};
int main()
{
LinkedList x;
x.insertAtHead(10);
x.insertAtHead(4);
x.insertAtBack(17);
// x.insertAtBack(22);
// x.insertAtBack(1);
// x.deleteValue(10);
x.printList();
return 0;
}