List not printing all the Elements - c++

So basically I created a linked list with the append and prepend functions and when I print the list it is only printing out 12 which I prepended to front of the list and not the other elements, how do I fix this issue? so that all the elements will be printed. I think that my append and prepend functions are correct but I do not know what could be wrong.
#include <iostream>
#include "List.h"
using namespace std;
int main() {
List* list = new List();
list->Append(1);
list->Append(2423);
list->Prepend(12);
list->print();
system("pause");
return 0;
}
#include<iostream>
#include "List.h"
using namespace std;
List::List() {
this->HEAD = NULL;
this->TAIL=NULL;
}
void List::Append(int Data_val) {
NODE* Current = new NODE;
Current->data = Data_val;
if (HEAD == NULL) {
HEAD = Current;
TAIL = Current;
Current->next = nullptr;
}
else {
TAIL->next= Current;
TAIL = Current;
Current->next = nullptr;
}
}
void List::Prepend(int data_val) {
NODE* Current = new NODE;
Current->data = data_val;
if (HEAD = NULL) {
Current->next = nullptr;
HEAD = Current;
TAIL = Current;
}
else {
Current->next = HEAD;
HEAD = Current;
Current->next = nullptr;
}
}
void List::print() {
NODE* Current = HEAD;
while (Current != NULL) {
cout << Current->data << endl;
Current=Current->next;
}
}
#ifndef LIST_H
#define LIST_H
struct NODE {
int data;
NODE* next;
};
class List
{
public:
List();
void Append(int data_val);
void Prepend(int data_val);
//create prepend
//create insertafter
//create delte
void print();
private:
//
NODE * HEAD;
NODE* TAIL;
};
#endif

You havae a bug with your List::Prepand() method. The "Current->next = nullptr;"
line is not needed within "else" block.
void List::Prepend(int data_val) {
NODE* Current = new NODE;
Current->data = data_val;
if (HEAD == NULL) {
Current->next = nullptr;
HEAD = TAIL = Current;
}
else {
Current->next = HEAD;
HEAD = Current;
Current->next = nullptr; // <---- remove this line
}
}

Related

why am i not getting output - Data Structure , Linked List

I tried to get output after call insertNodeToEnd and displayNode. Bu I did not get any output. What is problem here?
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void displayNode(Node* head ){
while(head!=NULL){//starting pointimiz NULL olana kadar döndür
cout<<head->data<<endl; //NULL olana kadar her Node'un data'sını yazdı
head = head->next;//ilerle
}
}
void insertNodeToEnd(Node*curr , int data){
while(curr->next !=NULL){
curr = curr->next;
}
curr ->next ->data = data;
curr ->next->next = NULL;
}
Node* head; //başlangıc node'unun adresini tuttuk
int main(){
Node* Head = new Node; //bir node oluşturduk
Head -> next = NULL;
Head -> data = 500; //oluşan node'un datasını oluşturduk
Node *iter = Head; //linked list içerisinde dolşacak iterator
//bu iterator'u head olarak tuttuk(artık döngüde iter'i başlangıç olarak kullanacağız)
int i = 0;
for(i = 0 ; i<5 ; i++){
insertNodeToEnd(iter,i*10);
}
displayNode(Head);
}
I tried to get output after call insertNodeToEnd and displayNode. Bu I did not get any output. What is problem here?
The problem is your insertNodeToEnd() is implemented all wrong. It is not creating a new Node, it is accessing curr->next when it is not pointing at a valid node, and it is not taking into account the possibility of head being NULL when the list is empty.
Try something more like this instead:
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void displayNodes(Node* head){
while (head != NULL){
cout << head->data << endl;
head = head->next;
}
}
void insertNodeToEnd(Node* &head, int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node *curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
/* alternatively:
void insertNodeToEnd(Node* &head, int data) {
Node **curr = &head;
while (*curr != NULL) {
curr = &((*curr)->next);
}
*curr = new Node;
(*curr)->data = data;
(*curr)->next = NULL;
}
*/
void freeNodes(Node* head){
while (head != NULL){
Node *next = head->next;
delete head;
head = next;
}
}
int main(){
Node* head = NULL;
insertNodeToEnd(head, 500);
for(int i = 0; i < 5; ++i){
insertNodeToEnd(head, i*10);
}
displayNodes(head);
freeNodes(head);
}
Online Demo
That being said, consider using the standard std::list container instead, eg:
#include <iostream>
#include <list>
using namespace std;
void displayNodes(const list<int> &lst){
for (int elem : lst){
cout << elem << endl;
}
}
int main(){
list<int> lst;
lst.push_back(500);
for(int i = 0; i < 5; ++i){
lst.push_back(i*10);
}
displayNodes(lst);
}
Online Demo

Linked List implementation of a Stack

Fairly new to implementing stacks and was looking for some possible feedback. My code gives the correct output, but I know this doesn't always mean it is working as it is suppose to. I chose to take the approach that implementing a stack using a linked list was essentially the same as your regular linked list implementation except that all the operations are done on the end of the list. I was not too sure if this approach was correct, but it followed the first in last out approach, and has the same complexity for access & search (O(n)) and insertion and deletion O(1). Such as pop() would just be deleting a node from the end of the linked list, and push() would just be appending a node to the end of the linked list. I have pasted my code below with comments within them explaining what I am doing or trying to do (if it is incorrect).
#include <iostream>
struct Node{
int data;
Node* next;
};
bool isEmpty(Node** stack){
if(*stack == NULL){
return true;
}
return false;
}
void push(Node** stack, int data){
Node* new_node = new Node();
new_node->data = data;
new_node->next=NULL;
// stack similar to "head"
if(isEmpty(&(*stack))){
*stack = new_node;
return;
}
Node* temp = *stack;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new_node;
}
void pop(Node** stack){
// checking if stack is empty
if(isEmpty(&(*stack))){
std::cout<<"Stack underflow"<<std::endl;
return;
}
Node* deleteMe = *stack;
// if at the first element in the stack
if(deleteMe->next == NULL){
*stack = (*stack)->next;
delete deleteMe;
return;
}
while(deleteMe->next != NULL){
if(deleteMe->next->next==NULL){
// saving the current location of the node before the node which I want to delete
Node* temp = deleteMe;
// updating the deleteMe pointer to the node which I want to delete
deleteMe = deleteMe->next;
// setting the current node before the deleteMe node to point to NULL instead of the node which I want to delete
temp->next = NULL;
delete deleteMe;
return;
}
deleteMe = deleteMe->next;
}
}
void printList(Node* stack){
Node* temp = stack;
while(temp!=NULL){
std::cout<<temp->data<<" ";
temp = temp->next;
}
std::cout<<"\n";
}
int top(Node** stack){
Node* top = *stack;
while(top->next!=NULL){
top = top->next;
}
return top->data;
}
int main(){
Node* stack = NULL;
// testing implementation below
push(&stack,10);
std::cout<<top(&stack)<<std::endl;
push(&stack,20);
std::cout<<top(&stack)<<std::endl;
push(&stack,30);
push(&stack,40);
printList(stack);
std::cout<<top(&stack)<<std::endl;
pop(&stack);
pop(&stack);
push(&stack,40);
std::cout<<top(&stack)<<std::endl;
}
Your implementation looks fine, one additional improvement can be done by maintaining head and tail pointer so that you can remove 1st and last element as needed. Here is example c++ code.
#include <iostream>
using namespace std;
template <class T> class node {
public:
node<T>() {}
~node<T>() {}
T data;
node<T> *next;
};
template <class T> class linked_list {
public:
linked_list<T>() : head(NULL), tail(NULL) {}
~linked_list<T>() {}
virtual void addFirst(T data) {
node<T> *n = new node<T>();
if (head == NULL)
tail = n;
n->data = data;
n->next = head;
head = n;
size++;
}
virtual void addLast(T data) {
node<T> *n = new node<T>();
n->data = data;
if (tail == NULL) {
head = n;
} else {
tail->next = n;
}
n->next = NULL;
tail = n;
}
virtual void reverse() {
if ((head == NULL) || (head->next == NULL))
return;
node<T> *current = head;
node<T> *previous = NULL;
node<T> *next = current->next;
tail = current;
while (current) {
next = current->next;
current->next = previous;
previous = current;
current = next;
}
head = previous;
}
virtual void print_nodes() {
node<T> *temp = head;
while (temp) {
cout << temp->data << " " << flush;
temp = temp->next;
}
cout << endl;
}
virtual void removeLast() {
node<T> *temp = head;
while (temp->next->next) {
temp = temp->next;
}
tail = temp;
delete temp->next;
temp->next = NULL;
}
virtual void removeFirst() {
node<T> *temp = head;
head = head->next;
delete temp;
}
private:
node<T> *head;
node<T> *tail;
uint32_t size;
};
int main(int argc, const char *argv[]) {
linked_list<uint32_t> *llist = new linked_list<uint32_t>();
llist->addLast(1);
llist->addFirst(5);
llist->addFirst(10);
llist->addFirst(15);
llist->addFirst(20);
llist->addLast(30);
llist->addFirst(40);
llist->print_nodes();
llist->reverse();
llist->print_nodes();
llist->removeLast();
llist->print_nodes();
llist->removeFirst();
llist->print_nodes();
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;
}

Print function doesn't terminate

I don't know why PrintList() doesn't terminate. It is a LinkedList, so when I go to next, that should terminate.
When I do AddNode once and then print, that terminates, when I do addNode twice, print doesn't terminate.
The reason why in constructor I create 5 empty spots is because I'm required to create those 5 empty spots when program starts.
Moreover, if for example I add twice , how I can assign pointer to that second value?
#pragma once
class LinkedList
{
private:
typedef struct node {
int data;
node* next;
}* nodePtr;
nodePtr n;
nodePtr head;
nodePtr curr;
nodePtr temp;
public:
LinkedList();
void AddNode(int addData);
void PrintList();
~LinkedList();
};
#include "LinkedList.h"
#include<cstdlib>
#include<iostream>
using namespace std;
LinkedList::LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
n = new node;
for (int x = 1; x <= 5; x++) {
//cout << n<<endl;
n->next = n;
}
}
void LinkedList::AddNode(int addData) {
//nodePtr n = new node;
n->next = NULL;
n->data = addData;
cout << n <<endl;
if (head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
void LinkedList::PrintList() {
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
LinkedList::~LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
delete n;
}
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "LinkedList.h"
using namespace std;
int main() {
LinkedList *l = new LinkedList();
l->AddNode(5);
l->AddNode(8);
l->PrintList();
system("pause");
return 0;
}
The node n is always the same since you are not setting n to a different node
So when you do n->next and n->data , the same node is being modified each time
void LinkedList::AddNode(int addData) {
//nodePtr n = new node; // you need to uncomment this
n->next = NULL;
n->data = addData;
cout << n <<endl;
if (head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
After your first addNode(5), lets examine the values.
head = n
head->data = 5
head->next = null
After your second addNode(8)
head = n
head->data = 8
head->next = n // set by "curr->next = n" .
So you have a problem here. When you try to loop through your linked list, it will become head->next->head->next->head->next->head->next ..... causing an infinite loop

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