Cannot Insert into Ordered Linked List - c++

I am writing a three file C++ program for my class. This program is ordered linked list. The program compiles but crashes when I attempt to insert (Run the program, select choice press enter, type an int to insert and press enter). Any help would be greatly appreciated.
Driver File:
#include "SortedLinkedList.h"
#include <iostream>
using namespace std;
int displayMenu();
void proccessChoice(int, SortedLinkedList&);
int main()
{
SortedLinkedList sSList;
int choice = displayMenu();
do
{
if (choice != 3)
{
proccessChoice(choice, sSList);
}
} while (choice != 3);
return 0;
}
void proccessChoice(int input, SortedLinkedList& l)
{
switch(input)
{
case 1:
int num;
cout << "Please enter a int: ";
cin >> num;
l.addItem(num);
break;
case 2:
l.popFirst();
break;
}
}
int displayMenu()
{
int choice;
cout << "menu" << endl;
cout << "===========" << endl;
cout << "1. add an int" << endl;
cout << "2. Show Sorted Linked List" << endl;
cout << "3. Exit" << endl;
cin >> choice;
cin.ignore();
return choice;
}
Declaration File:
struct sslNode
{
sslNode* next;
int item;
};
class SortedLinkedList
{
private:
sslNode* head;
bool isEmpty ();
public:
SortedLinkedList();
~SortedLinkedList();
void addItem(int);
int popFirst();
};
Implementation File:
#include <iostream>
using namespace std;
#include "SortedLinkedList.h"
SortedLinkedList::SortedLinkedList()
{
head = NULL;
}
SortedLinkedList::~SortedLinkedList()
{
sslNode *temp, *nextLink;
nextLink = head;
while(nextLink != NULL)
{
temp = nextLink->next;
delete nextLink;
nextLink = temp;
}
}
bool SortedLinkedList::isEmpty()
{
return (head == NULL);
}
void SortedLinkedList::addItem(int itemToInsert)
{
sslNode* cur;
sslNode* prev;
sslNode* newNode = new sslNode();
newNode->item = itemToInsert;
newNode->next = NULL;
cur = head;
prev = NULL;
bool moreToSearch (cur != NULL);
while (moreToSearch) //Find insertion point
{
if (cur->item > newNode->item) // while current location has a greater value then what needs to be inserted move pointers forward.
{
prev = cur;
cur = cur->next;
moreToSearch = (cur != NULL);
}
else // if current loacation and what is to be inserted are equal or less then we have found the point of insertion
{
moreToSearch = false;
}
}
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
//Insert as only item in list
//Insert in found location
}
int SortedLinkedList::popFirst()
{
sslNode* first;
first = head->next;
head = head->next;
int item = first->item;
return item;
}

Your problem is you forgot an =
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
if(prev = NULL)
should be
if(prev == NULL)
right now this is always false because prev becomes null which evaluates to false
and then it fails at
prev->next = newNode;
because your are dereferencing the null pointer.
You'll also want to treat the case where head == NULL before trying to insert anything. Basically if head == NULL, head = newNode;

It crashes because head is initialized to NULL. You probably want to make a dummy head node, depending on your design, or check if its NULL before using it in addItem().
This is how things go down:
SortedLinkedLis
t::SortedLinkedList() // ctor is called
...
head = NULL
SortedLinkedList::addItem(int)
sslNode* cur;
...
cur = head;
...
bool moreToSearch (cur != NULL) // this is surely false
...
if (prev = NULL)
{
newNode->next = head->next;
...//BUT head == NULL ! crash!

Related

modify the linked list main function code in which user will input the index and data of the node with proper messages

I have a link list in which user will input the index and data of the node with proper messages....
it is a very simple task i know but i am so confuse how to do it .
all i want is that you edit my code so that user can enter which index he/she want to enter data and also he/she is able to enter his/her data..
I'll be very great full if some one reply .
#include <iostream>
using namespace std;
class Node {
public:
double data; // data
Node* next; // pointer to next
};
class List {
public:
List(void) { head = NULL; } // constructor
~List(void); // destructor
bool IsEmpty() { return head == NULL; }
Node* InsertNode(int index, double x);
int FindNode(double x);
int DeleteNode(double x);
void DisplayList(void);
private:
Node* head;
};
Node* List::InsertNode(int index, double x)
{
if (index < 0)
return NULL;
int currIndex = 1;
Node* currNode = head;
while (currNode && index > currIndex) {
//Try to locate index'th node. If it doesn't exist, return NULL
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL)
return NULL;
Node* newNode = new Node;
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
int List::FindNode(double x)
{
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
currNode = currNode->next;
currIndex++;
}
if (currNode)
return currIndex;
return 0;
}
int List::DeleteNode(double x)
{
Node* prevNode = NULL;
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode) {
if (prevNode) {
prevNode->next = currNode->next;
delete currNode;
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
void List::DisplayList()
{
int num = 0;
Node* currNode = head;
while (currNode != NULL) {
cout << currNode->data << endl;
currNode = currNode->next;
num++;
}
cout << "Number of nodes in the list: " << num << endl;
}
List::~List(void)
{
Node* currNode = head;
Node* nextNode = NULL;
while (currNode != NULL) {
nextNode = currNode->next;
delete currNode; // destroy the current node
currNode = nextNode;
}
}
int main(void)
{
List list;
list.InsertNode(0, 7.0); // successful
list.InsertNode(1, 5.0); // successful
list.InsertNode(-1, 5.0); // unsuccessful
list.InsertNode(0, 6.0); // successful
list.InsertNode(8, 4.0); // unsuccessful
// print all the elements
list.DisplayList();
if (list.FindNode(5.0) > 0)
cout << "5.0 found" << endl;
else
cout << "5.0 not found" << endl;
if (list.FindNode(4.5) > 0)
cout << "4.5 found" << endl;
else
cout << "4.5 not found" << endl;
list.DeleteNode(7.0);
list.DisplayList();
return 0;
}
Just read in the input and call the method on the list object. What did you find so confusing about it?
Also, try to get out of the habit of using namespace std! Append this code to the main function.
int index;
double data;
std::cout << "Enter the index: ";
std::cin >> index;
std::cout << "Enter data: ";
std::cin >> data;
list.InsertNode(index, data);
list.DisplayList();
Declare temporary variables index and data to hold the input from the console.
Print to the console asking the user to enter the index and data using std::cout , which is at the position at which the node is to be entered. std::cin can be used to read input from the console and store it in a variable
The nodes of your linked list contain a data field of type double which is the actual data of your linked list. Using your list object, you call the InsertNode() method along with this index and data.
Don't worry it a very simple task
1:- firstly you should give values in particulate index
2:- ten just fetch it from the particular index
for further information you can contact

my code stops in the middle and has no error c++

case 1 work fine but case 2 and 3 just stop the loop and the program
and i cannot choose any other case after that as! i wonder why it stop the loop from going as choice here would never equal 0 which i believe it's the only reason would stop the loop from going forward! thanks in advance.
i also checked the functions and all of them seems fine to me i'm not sure if the problem could be with them
#include "stdafx.h"
#include <iostream>
using namespace std;
void insert_node(int new_data);
void print_node();
void delete_node();
int new_data;
char choice;
struct node {
int data;
node* next;
};
node* head = NULL;
void main()
{
do
{
cout << "Enter 1 to insert a new node \n";
cout << "Enter 2 to disply the list \n";
cout << "Enter 3 to delete the last node \n";
cin >> choice;
switch (choice)
{
case '1':
cout << "Enter the data \n";
cin >> new_data;
insert_node(new_data);
break;
case '2':
if (head != NULL)
print_node();
else
cout << "SORRY, your list is empty \n";
break;
case '3':
delete_node();
break;
default:
cout << "Invalid entry \n";
}
} while (choice != '0');
}
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
void print_node()
{
node* printer=head;
do
{
cout << printer->data<<" - ";
printer = printer->next;
} while (printer != NULL);
}
void delete_node()
{
if (head == NULL)
cout << "no node to be deleted \n";
else
{
node* curr = head;
node* prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
if (prev == NULL)
{
delete(curr);
head = NULL;
return;
}
prev->next = NULL;
delete(curr);
}
}
This is bugged
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
it should be
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
NewNode->next = head;
head = NewNode;
}
Your version fails to set next when adding the first node to the list. And as you can see there's no need to make head == NULL a special case.
Because you aren't creating the list correctly in the first place, any attempt to print or delete items from the list is likely to fail.
And your print_node function would fail on an empty list. It should be a while loop not a do ... while loop.
void print_node()
{
node* printer=head;
while (printer != NULL)
{
cout << printer->data<<" - ";
printer = printer->next;
}
}
Your delete_node function looks very suspicious to me as well.

How to display a message saying doubly linked list is empty,cannot delete element from it?

I have implemented a sorted doubly linked list with the help of pointers in C++.I want to display an error message on deleting the last element saying "doubly linked list is empty cannot delete any more elements" and also display a message before deleting the last element saying"the last element in the node are you sure you want to delete it"?
#include "stdafx.h"
#include "DoublyLinkedList.h"
#include<iostream>
using namespace std;
DoublyLinkedList::DoublyLinkedList():Head(nullptr),Tail(nullptr) {
}
DoublyLinkedList::~DoublyLinkedList() {
Node *current = Head;
while (current != NULL)
{
Node* next = current->Next; //The objects pointed to by head and tail at the beginning of the destructor are deleted
Node* prev = current->Prev; // through the current pointer. Then they are deleted again at the end of the destructor.
delete current;
current = next;
current = prev;
}
}
void DoublyLinkedList::SortedInsert(const int& new_element) {
if(new_element !=0){
Node* np = new Node(new_element);
if (!Head)
{
Head = np;
Tail = np;
}
else if (new_element < Head->Element)
{
np->Next = Head;
Head->Prev = np;
Head = np;
}
else
{
Node *cur = Head->Next;
while ((cur) && (new_element >= cur->Element))
cur = cur->Next;
if (cur)
{
np->Prev = cur->Prev;
np->Next = cur;
cur->Prev->Next = np;
cur->Prev = np;
}
else
{
Tail->Next = np;
np->Prev = Tail;
Tail = np;
}
}
}
}
void DoublyLinkedList::Delete(const int& del_element)
{
Node *cur = Head;
while (cur)
{
if (cur->Element == del_element)
{
if (cur->Prev)
cur->Prev->Next = cur->Next;
if (cur->Next)
cur->Next->Prev = cur->Prev;
if (cur == Head)
Head = cur->Next;
if (cur == Tail)
Tail = cur->Prev;
delete cur;
break;
}
cur = cur->Next;
}
}
void DoublyLinkedList::traverse_head() {
Node *t = Head;
while (t != NULL)
{
cout << t->Element << "\t";
t = t->Next;
}
cout << endl;
}
void DoublyLinkedList::traverse_tail() {
Node *temp = Tail;
while (temp != NULL) {
cout << temp->Element << "\t";
temp = temp->Prev;
}
}
main.cpp
// Question1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include"DoublyLinkedList.h"
#include<iostream>
using namespace std;
int main()
{
DoublyLinkedList intlist;
int i = 0, x=0,delete_elm=0;
//intlist.SortedInsert(3);
//intlist.SortedInsert(6);
//intlist.SortedInsert(7);
//intlist.SortedInsert(10);
//intlist.SortedInsert(-1);
//intlist.traverse_head();
do
{
cout << "\nEnter value of node.Press 0 to stop\n";
cin >> x;
if ((!cin) || cin.peek() != '\n') {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input, no string allowed!!" << endl;
}
else {
intlist.SortedInsert(x);
i++;
}
} while (x != 0);
intlist.traverse_head();
cout << "\nTraversing Doubly Linked List head first\n";
intlist.traverse_head();
cout << "\nTraversing Doubly Linked List tail first\n";
intlist.traverse_tail();
cout << endl;
do {
cout << "Which element do you want to delete? 0 to stop delete operation" << endl;
cin >> delete_elm;
cout << endl;
if ((!cin) || cin.peek() != '\n' || x < 0) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input, no string allowed!!" << endl;
}
else {
intlist.Delete(delete_elm);
cout << "\nTraversing Doubly Linked List head first\n";
intlist.traverse_head();
cout << "\nTraversing Doubly Linked List tail first\n";
intlist.traverse_tail();
cout << endl;
}
} while (delete_elm != 0);
system("pause");
return 0;
}
Since you seem to not be using dummy nodes, checking if the list is empty is the same as checking if the Head or Tail pointers are null. Checking if it's only one element is the same as checking if Head->Next is null (be sure to check that Head is not null first, of course).
Alternatively, you can maintain a size variable (incremented in insert and decremented in remove) or write a method to calculate the size by traversing the list.

Ordered Linked List errors

I know all of the code isn't working but when I first run the program and the first string is read in from the text field the program errors out.The main function is passing the string to "Insert list function" in the implementation.
The program is suppose to insert a node every time that a string is read in from the text file. The program call also call the delete function which i know isn't working yet(that is why it is commented out). I am just trying to find the error that is created when the insert function is called. The main function has a while loop that creates a Node for every text entry and passes the node one by one to be sorted in ABC order.
Header file:
#include <string>
using namespace std;
struct Node
{
string data;
Node * next;
};
class List
{
public:
List();
~List();
bool Insert(string);
bool Delete(string);
void Print();
bool Edit(string, string);
private:
Node * head;
Node * cur;
Node * trailer;
};
Implementation:
#include <iostream>
#include <string>
#include <fstream>
#include "List.h"
using namespace std;
List::List():head(NULL)
{}
List::~List()
{}
bool List::Insert(string data)
{
Node* newNode = new Node;
if (newNode == NULL)
{
cout << "Error: Memory Allocation Failed" << endl;
return false;
}
newNode->data = data;
cur = head;
trailer = NULL;
if (head == NULL)
{
//cout << "head is Null" << endl;
head = newNode;
cout << head -> data << endl;
newNode->next = NULL;
//return true;
}
while (newNode->data > cur->data && cur -> next != NULL)
{
trailer = cur;
cur = cur->next;
}
if (cur->next == NULL)
{
cur->next = newNode;
newNode->next = NULL;
return true;
}
else
{
trailer->next = newNode;
newNode->next = cur;
return true;
}
}
bool List::Delete(string data)
{
/*Node *temp = head->next;
while (head != NULL)
{
delete head;
head = temp;
temp = head->next;
}
return true;*/
}
bool List::Edit(string dataDelete, string dataInsert)
{
Delete(dataDelete);
Insert(dataInsert);
return true;
}
void List::Print()
{
for (Node * Count = head; Count != NULL; Count = Count->next)
{
cout << Count->data << endl;
}
}
#Deepak is right, the problem is when you're inserting first element the head variable is NULL and cur is set to the value of head.
To fix it you can simply place
cur = head;
trailer = NULL;
after condition
if (head == NULL)
{
//cout << "head is Null" << endl;
head = newNode;
cout << head -> data << endl;
newNode->next = NULL;
//return true;
}
Also there will be an error when you will try to insert element that should be placed in the beggining (value that is smaller than any other value in the list). It will happen when condition of the loop
trailer = NULL;
while (newNode->data > cur->data && cur -> next != NULL) { ... }
is false in the first call, so trailer will be NULL. To fix it you will need to check trailer variable, like this
if (trailer == NULL) {
newNode->next = head;
head = newNode;
return true;
}
As the result your code of Insert will look like
bool List::Insert(string data)
{
Node* newNode = new Node;
if (newNode == NULL)
{
cout << "Error: Memory Allocation Failed" << endl;
return false;
}
newNode->data = data;
if (head == NULL)
{
head = newNode;
newNode->next = NULL;
return true;
}
cur = head;
trailer = NULL;
while (newNode->data > cur->data && cur -> next != NULL)
{
trailer = cur;
cur = cur->next;
}
if (trailer == NULL) {
newNode->next = head;
head = newNode;
return true;
}
if (cur->next == NULL)
{
cur->next = newNode;
newNode->next = NULL;
return true;
}
else
{
trailer->next = newNode;
newNode->next = cur;
return true;
}
}
While inserting the first node you are getting error because of
while (newNode->data > cur->data && cur -> next != NULL)
At this moment value in the cur is NULL and you are trying to access cur->data.

Access violation error while creating linked list

Trying to create Lined List. I am having problem in the deleteNode function created in LinkedList.cpp file. Experiencing given error
Unhandled exception at 0x00D04C3C in LinkedList.exe: 0xC0000005:
Access violation reading location 0x00000004.
previous->link = temp->link;
LinkedList.h file
class Node
{
public:
int data;
Node *link;
};
class LList
{
private:
Node *Head, *Tail;
//void recursiveTraverse(Node *);
public:
LList();
~LList();
void create();
Node *getNode();
void append(Node *);
void insert(Node *, int);
void rtraverse();
void deleteNode(int);
void display();
};
LinkedList.cpp
#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
LList::LList()
{
Head = nullptr; Tail = nullptr;
}
LList::~LList()
{
Node *Temp;
while (Head != nullptr)
{
Temp = Head;
Head = Head->link;
delete Temp;
}
}
void LList::create()
{
char choice;
Node *newNode = nullptr;
while (5)
{
cout << "Enter Data in the List (Enter N to cancel) ";
cin >> choice;
if (choice == 'n' || choice == 'N')
{
break;
}
newNode = getNode();
append(newNode);
}
}
Node *LList::getNode()
{
Node *temp = new Node;
//cout << "Enter Data in the List";
cin >> temp->data;
temp->link = nullptr;
return temp;
}
void LList::append(Node *temp)
{
if (Head == nullptr)
{
Head = temp;
Tail = temp;
}
else
{
Tail->link = temp;
Tail = temp;
}
}
void LList::display()
{
Node *temp = Head;
if (temp == nullptr)
{
cout << "No Item in the List" << endl;
}
else
{
while (temp != nullptr)
{
cout << temp->data << "\t";
temp = temp->link;
}
cout << endl;
}
}
void LList::insert(Node *newNode, int position)
{
int count = 0; Node *temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
Head = newNode;
Tail = newNode;
}
else
{
while (temp == nullptr || count < position)
{
count++;
previous = temp;
temp = temp->link;
}
previous->link = newNode;
newNode->link = temp;
}
}
void LList::deleteNode(int position)
{
int count = 1; Node * temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
cout << "No Data to delete." << endl;
}
else
{
while (count <= position + 1)
{
if (position == count + 1)
{
count++;
previous = temp;
previous->link = temp->link;
}
else if (count == position + 1)
{
count++;
previous->link = temp->link;
}
count++;
temp = temp->link;
}
}
}
Main.cpp goes here
I see multiple things wrong here, any one of which could be causing your problem. If they don't fix it I could take another look if someone else doesn't get to it first.
First and foremost, your if statements in your delete function will always execute. Because you are assigning instead of checking for equality, ie '=' instead of '=='. This alone may fix the issue.
The other thing that jumps out of the page is that you are obviously dynamically allocating each node, and your delete function should be delete'ing the memory once you are done with it.
Fix those two first and then see where you are at.
Looks like temp cannot be a nullpointer at the line giving an error, but previous might be.
Important: Note that the line
else if (count = position + 1)
Is actually an assignment. You probably meant
else if (count == position + 1)
The same goes for the if statement before that.
Cheers!