Access violation error while creating linked list - c++

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!

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

deleting a linked list node, C++ function not working

#include <iostream>
using namespace std;
class List {
public:
struct node {
int data;
node *next;
};
node* head = NULL;
node* tail = NULL;
node* temp = NULL;
node* prev = NULL;
public:
void addNum(int num) {
temp = new node;
temp->data = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
}
void PrintList() {
temp = head;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
}
void DelNum(int num) {
temp = head;
while (temp != NULL) {
if (temp->data == num) {
prev->next = temp->next;
free(temp);
}
temp = prev;
temp = temp->next;
}
}
};
int main() {
List list;
list.addNum(1);
list.addNum(2);
list.addNum(3);
list.addNum(4);
list.addNum(5);
list.addNum(6);
list.DelNum(3);
list.PrintList();
return 0;
}
What is wrong with my DelNum function? When I run the program nothing pops up. Doesn't matter what number I put in.
As mss pointed out the problem is in your DelNum() function where you assign temp = prev;. In your initialization you defined that node* prev = NULL; So, prev = NULL at the point when you assigned it to temp which caused segmentation fault when you try to use it like temp = temp->next;.
Two main problems are there in DelNum function:
first, when you are in while loop
, you should assign
prev = temp;
second, when you have found your target element, after deleting it you have to break out of the loop, which isn't done in your code
below is your corrected code( also correction of some other corner case in DelNum function ):
#include <iostream>
using namespace std;
class List {
public:
struct node {
int data;
node *next;
};
node* head = NULL;
node* tail = NULL;
node* temp = NULL;
node* prev = NULL;
public:
void addNum(int num) {
temp = new node;
temp->data = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
cout<<num<<" is added \n";
}
void PrintList() {
temp = head;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->next;
}
}
void DelNum(int num) {
if(head==NULL)//empty
{
cout<<"empty linked list, can't be deleted\n";
return;
}
if(head->next==NULL)//means only one element is left
{
if(head->data==num)
{
node * fordelete=head;
head=NULL;
cout<<num<<"is deleted\n";
delete(fordelete);
}
else
{
cout<<"not found , can't be deleted\n";
}
return;
}
temp = head; // when more than one element are there
prev = temp;
while (temp != NULL) {
if (temp->data == num) {
prev->next = temp->next;
free(temp);
cout<<num<<" is deleted\n";
break;
}
prev= temp;
temp = temp->next;
}
if(temp==NULL)
{
cout<<"not found, can't be deleted\n";
}
}
};
int main() {
List list;
list.addNum(1);
list.addNum(2);
list.addNum(3);
list.addNum(4);
list.addNum(5);
list.addNum(6);
list.PrintList();
list.DelNum(3);
list.DelNum(7);
list.PrintList();
return 0;
}
I hope it will help you.

Linked List Crashes after all nodes are deleted

Our homework assignment wanted us to create a "Staque" (implements features of a stack and a queue) using a linked list. When entering even numbers in the list, they should go to the top of the list and odd numbers at the bottom. So if the values inserted are 8 1 4 6 7 9 it should output 6 4 8 1 7 9. Then you delete the top two even numbers and the bottom odd number which would give 8 1 7. Everything seems to work fine except when all the nodes are deleted so when you enter 3 or less values, the program crashes. At this time I have to turn in my assignment since it's due tonight but am just wondering how this can be resolved. Any help would be appreciated.
Here is my code:
Driver:
#include <iostream>
#include "Staq.h"
using namespace std;
int main()
{
Staq *std = new Staq();
int numofvals;
int i;
int x;
cout << "How many values in the staque?" << endl;
cin >> numofvals;
cout << numofvals << " values will be entered in the staque." << endl << endl;;
for(i=1; i<=numofvals; i++)
{
cout << "Enter value " << i << ":" << endl;
cin >> x;
std->AddNode(x);
}
cout << endl;
cout << "Staque:" << endl;
std->PrintList();
std->DeleteNode();
cout << "\nStaque after deletions:" << endl;
std->PrintList();
return 0;
}
.CPP:
#include <iostream>
using namespace std;
#include "Staq.h"
Staq::Staq()
{
head = NULL;
curr = NULL;
temp = NULL;
}
void Staq::AddNode(int addData)
{
nodePtr n = new node;
n->next = NULL;
n->data = addData;
if(addData % 2 == 0)
{
if(head == NULL)
{
head = n;
curr = n;
}
else
{
n->next = head;
head = n;
}
}
else
{
if(head == NULL)
{
head = n;
curr = n;
}
else
{
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
}
}
void Staq::DeleteNode()
{
nodePtr temp2 = new node;
if(head->data %2 == 0)
{
temp = head;
head = head->next;
delete temp;
if(head->data %2 == 0)
{
temp = head;
head = head->next;
delete temp;
}
}
temp = head;
while(temp->next->next != NULL)
{
temp = temp->next;
}
if(temp->data %2 != 0)
{
temp2 = temp->next;
temp->next = NULL;
delete temp2;
}
}
void Staq::PrintList()
{
curr = head;
while(curr != NULL)
{
cout << curr->data << endl;
curr = curr->next;
}
}
Header:
#include <iostream>
using namespace std;
#ifndef STAQ_H
#define STAQ_H
class Staq
{
public:
Staq();
~Staq();
void AddNode(int addData);
void DeleteNode();
void PrintList();
private:
class node
{
public:
int data;
node* next;
};
typedef class node* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
};
#endif
In DeleteNode, you attempt to access the first node's data, even if there isn't a node. Same goes for the second node.
while(temp->next->next) is dangerous because temp->next could be NULL therefore making temp->next->next an access to null pointer. I assume you meant temp->next. You might want to validate temp too.
Finally, although unrelated, temp2 = temp->next causes a memory leak because now no one points to the new node created at the beginning of DeleteNode.

Linked List insertion/deletion

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL;
int size;
Node* tail = NULL;
void printLinkedList() {
Node *search = head;
if (head == NULL) {
cout << "linkedlist is empty" << endl;
}
else {
while (search != NULL){
cout << search->data << endl;
search = search->next;
}
}
}
int sizeLinkedList() {
size = 1;
Node* current = head;
while (current->next != NULL) {
current = current->next;
size = size + 1;
}
cout << size << endl;
return size;
}
Node *getNode(int position){
Node *current = head;
for (int i = 0; i<position; i++)
{
current = current->next;
}
return current;
}
void appendNode(int n) {
Node *newNode = new Node; //creating new node
newNode->data = n;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
return;
}
else {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void insertNode(int n, int position) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
int size = sizeLinkedList();
if (position = 0){
if (head == NULL) {
head = newNode;
}
else{
newNode->next = head;
head = newNode;
}
}
else if (position == size) {
appendNode(n);
}
else {
Node *prevNode = getNode(position-1);
Node *nextNode = getNode(position);
prevNode->next = newNode;
newNode->next = nextNode;
}
}
void deleteNode(int position) {
Node *currentNode;
int size = sizeLinkedList();
if (size == 0) {
return;
}
if (position == 0) {
currentNode = head->next;
head = currentNode;
}
else if (position == size-1) {
getNode(position - 1)->next = NULL;
delete getNode(position);
}
else {
getNode(position - 1)->next = getNode(position+1);
delete getNode(position);
}
}
//making a dynamic array only via pointers in VC++
void makeArray() {
int* m = NULL;
int n;
cout << "how many entries are there?"<<endl;
cin >> n;
m = new int[n];
int temp;
for (int x = 0; x < n; x++){
cout << "enter item:"<< x+1<< endl;
cin >> temp;
*(m + x) = temp;
}
for (int x = 0; x < n; x++){
cout << x+1 + ":" << "There is item: "<<*(m+x) << endl;
}
delete[]m;
}
int main() {
int x;
//makeArray();
appendNode(1);
appendNode(2);
appendNode(32);
appendNode(55);
appendNode(66);
//insertNode(2, 0);
printLinkedList();
deleteNode(3);
printLinkedList();
sizeLinkedList();
cin >> x;
}
Im just trying to code a Linked List with a couple of functions for practice
My Delete function, the last else statement isnt working, and logically I cant figure out why,
as for my insert function none of the statements are working, not even at head or position 0. However appending items, returning size, printing the list, deleting the first and last elements works.
thanks!
sizeLinkedList won't work correctly if the list is empty (it cannot return 0)
you are using size as different variables at different scopes (at main scope, and within deleteNode). This is pretty confusing although not strictly wrong.
in deleteNode, this sequence won't work:
else if (position == size-1) {
getNode(position - 1)->next = NULL;
delete getNode(position);
}
setting the next pointer on the node prior to position to NULL will interfere with the attempt to getNode(position) in the very next line, because it traverses the list based on next. The fix is to reverse these two lines.
Likewise, your last sequence in deleteNode won't work for a similar reason, because you are modifying the next pointers:
else {
getNode(position - 1)->next = getNode(position+1);
delete getNode(position); // this list traversal will skip the node to delete!
}
the solution here is like this:
else {
currentNode = getNode(position);
getNode(position - 1)->next = getNode(position+1);
delete currentNode;
}
I've also re-written the insertNode function incorporating the comment provided by #0x499602D2 .
Here's a modified version of your code that has your current sequence in main fixed:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL;
int size = 0;
Node* tail = NULL;
void printLinkedList() {
Node *search = head;
if (head == NULL) {
cout << "linkedlist is empty" << endl;
}
else {
while (search != NULL){
cout << search->data << endl;
search = search->next;
}
}
}
int sizeLinkedList() {
size = 0;
if (head->next != NULL){
size = 1;
Node* current = head;
while (current->next != NULL) {
current = current->next;
size = size + 1;
}
}
cout << size << endl;
return size;
}
Node *getNode(int position){
Node *current = head;
for (int i = 0; i<position; i++)
{
current = current->next;
}
return current;
}
void appendNode(int n) {
Node *newNode = new Node; //creating new node
newNode->data = n;
newNode->next = NULL;
size++;
if (head == NULL)
{
head = newNode;
return;
}
else {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void insertNode(int n, int position) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
if (position == 0){
newNode->next = head;
head = newNode;
}
else if (position == sizeLinkedList()) {
appendNode(n);
}
else {
Node *prevNode = getNode(position-1);
Node *nextNode = getNode(position);
prevNode->next = newNode;
newNode->next = nextNode;
}
}
void deleteNode(int position) {
Node *currentNode;
int my_size = sizeLinkedList();
if ((my_size == 0) || (position > my_size)) {
return;
}
if (position == 0) {
currentNode = head->next;
head = currentNode;
}
else if (position == size-1) {
delete getNode(position);
getNode(position - 1)->next = NULL;
}
else {
currentNode = getNode(position);
getNode(position - 1)->next = getNode(position+1);
delete currentNode;
}
}
//making a dynamic array only via pointers in VC++
void makeArray() {
int* m = NULL;
int n;
cout << "how many entries are there?"<<endl;
cin >> n;
m = new int[n];
int temp;
for (int x = 0; x < n; x++){
cout << "enter item:"<< x+1<< endl;
cin >> temp;
*(m + x) = temp;
}
for (int x = 0; x < n; x++){
cout << x+1 + ":" << "There is item: "<<*(m+x) << endl;
}
delete[]m;
}
int main() {
int x;
//makeArray();
appendNode(1);
appendNode(2);
appendNode(32);
appendNode(55);
appendNode(66);
insertNode(2, 0);
printLinkedList();
deleteNode(3);
printLinkedList();
sizeLinkedList();
}

Cannot Insert into Ordered Linked List

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!