Linked List insertion/deletion - c++

// 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();
}

Related

C++ Inserting into a linked list

I am writing a program that modifies a linked list. The problem I am having is when inserting nodes into the linked list. The first few nodes are inserted and moved properly, but when reaching the end of the linked list some nodes are either removed or not displayed.
Function for inserting
void LinkedList::insert(int num, int pos)
{
Node *temp1 = new Node;
temp1->data = num;
temp1->next = NULL;
if(pos == 0)
{
temp1->next = head;
head = temp1;
return;
}
Node *temp2 = head;
for(int i = 0; i < pos-1; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
Node structure
struct Node
{
int data;
Node *next;
};
int size;
Node *head, *tail;
Driver code
nums.insert(1, 0); // 1 in location 0
nums.insert(5, 4); // 5 in location 4
nums.insert(3, 7); // 3 in location 7
List before insert
8 6 7 8 0 9
List after insert
1 8 6 7 5 8
Expected after insert
1 8 6 7 5 8 0 9 3
Would the values excluded from being display needed to be stored and inserted afterwards? Or is the inserting itself not being coded properly/missing elements?
Thanks for your help.
Full code
#include "linkedlist.h"
LinkedList::LinkedList()
{
head = nullptr;
tail = nullptr;
size = 0;
}
LinkedList::~LinkedList()
{
if(head != nullptr)
{
Node *temp;
while(head != nullptr)
{
temp = head->next;
// deletes head
delete head;
// goes to next element
head = temp;
}
}
}
void LinkedList::display()
{
Node *temp = head;
for(int i = 0; i < size; i++)
{
cout << temp->data << "\t";
temp = temp->next;
}
cout << endl;
}
void LinkedList::append(int num)
{
// list is empty
if(head == nullptr)
{
head = new Node;
head->data = num;
head->next = nullptr;
// sets tail to head
tail = head;
}
else
{
// creates new node
Node *temp = new Node;
// sets new node data
temp->data = num;
temp->next = nullptr;
// sets previous tail link to new node
tail->next = temp;
// sets this node to new tail
tail = temp;
}
// increments size
size++;
}
void LinkedList::pop()
{
if(size > 1)
{
Node *temp = head;
// loops to node before tail
while(temp->next->next != nullptr)
{
temp = temp->next;
}
// deletes tail
delete tail;
// sets new tail
tail = temp;
tail->next = nullptr;
}
// if there's only one item
else if(size == 1)
{
Node *temp = tail;
// head and tail are now null
head = nullptr;
tail = nullptr;
// deletes node
delete temp;
}
size--;
}
int LinkedList::min()
{
int min = head->data;
struct Node *temp = head;
while(temp != nullptr)
{
if(min > temp->data)
{
min = temp->data;
}
temp = temp->next;
}
return min;
}
int LinkedList::max()
{
int max = head->data;
struct Node *temp = head;
while(temp != nullptr)
{
if(max < temp->data)
{
max = temp->data;
}
temp = temp->next;
}
return max;
}
int LinkedList::mean()
{
int sum = 0;
int average = 0;
struct Node *temp = head;
while(temp != nullptr)
{
sum += temp->data;
temp = temp->next;
}
average = sum / size;
return average;
}
void LinkedList::sort()
{
Node *current1 = head;
Node *current2 = head;
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size - 1; j++)
{
if(current1->data < current2->data)
{
int temp = current1->data;
current1->data = current2->data;
current2->data = temp;
}
current2 = current2->next;
}
current2 = head;
current1 = head->next;
for(int p = 0; p < i; p++)
{
current1 = current1->next;
}
}
}
void LinkedList::reverse()
{
Node *current1 = head;
Node *current2 = head;
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size - 1; j++)
{
if(current1->data > current2->data)
{
int temp = current1->data;
current1->data = current2->data;
current2->data = temp;
}
current2 = current2->next;
}
current2 = head;
current1 = head->next;
for(int p = 0; p < i; p++)
{
current1 = current1->next;
}
}
}
int LinkedList::linearSearch(int key)
{
Node *search = nullptr;
Node *temp = head;
Node *current = head;
int count = 0;
while(current != NULL && current->data != key)
{
count++;
temp = current;
current = current->next;
}
if(current != NULL)
{
search = current;
current = current->next;
}
key = count;
return key;
}
void LinkedList::insert(int num, int pos)
{
Node *temp1 = new Node;
temp1->data = num;
temp1->next = NULL;
if(pos == 0)
{
temp1->next = head;
head = temp1;
return;
}
Node *temp2 = head;
for(int i = 0; i < pos-1; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
You have a size member that your display function uses, but you never increment it in insert. So while the element gets added, you don't increase the size of the list.
Reading your whole code and getting to the solution may consume lot of time but if you want i have a code ready which is properly working. If you wanted to use this. Please go for it and also, please feel free to ask my anything though this link
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
node* gethead()
{
return head;
}
static void display(node *head)
{
if(head == NULL)
{
cout << "NULL" << endl;
}
else
{
cout << head->data << endl;
display(head->next);
}
}
static void concatenate(node *a,node *b)
{
if( a != NULL && b!= NULL )
{
if (a->next == NULL)
a->next = b;
else
concatenate(a->next,b);
}
else
{
cout << "Either a or b is NULL\n";
}
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
linked_list b;
b.add_node(3);
b.add_node(4);
linked_list::concatenate(a.gethead(),b.gethead());
linked_list::display(a.gethead());
return 0;
}

How to sort doubly linked list in c++ without swapping data, only transferring (entries) nodes

I have got a problem in the sorting method of my linked list. I need to sort nodes in a doubly linked list by transferring links of nodes (entries of nodes). The method is stopped due to nullptr in the last node.
I do not know how to solve this problem. I tried a lot of variants, but no one was successful.
#include "DlinkedList.h"
// Node constructor
Node::Node()
{
this->rhetorician = NULL;
this->prev = NULL;
this->next = NULL;
}
// Node destructor
Node::~Node()
{
}
// List constructor
DlinkedList::DlinkedList()
{
this->length = 0;
this->head = NULL;
}
// Method for adding node at the end
void DlinkedList::appendNode(Rhetorician* rhetorician)
{
if (this->head == NULL) {
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
this->head = new_node;
}
else {
Node *last_node = NULL;
for (Node *node_ptr = this->head; node_ptr != NULL; node_ptr = node_ptr->next)
{
last_node = node_ptr;
}
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
last_node->next = new_node;
new_node->prev = last_node;
}
this->length++;
}
// Method for printing nodes
void DlinkedList::printNodes()
{
for (Node *node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
node_cur->rhetorician->printer();
cout << "---------------------------------------------------------------------------------------------------" << endl;
}
cout << endl << "##################################################################################################\n" << endl;
}
// Method for getting length
int DlinkedList::getLenght()
{
return this->length;
}
// Method for deleting node
void DlinkedList::remove(string name)
{
Node* logout_node = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
logout_node = node_cur;
}
}
if (this->head != NULL || logout_node != NULL)
{
if (this->head == logout_node)
{
this->head = logout_node->next;
}
if (logout_node->next != NULL)
{
logout_node->next->prev = logout_node->prev;
}
if (logout_node->prev != NULL)
{
logout_node->prev->next = logout_node->next;
}
delete logout_node->rhetorician;
delete logout_node;
this->length--;
}
}
// Method for finding node
void DlinkedList::find(string name)
{
bool ver = false;
Node *n = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
ver = true;
n = node_cur;
}
}
if (ver)
{
n->rhetorician->printer();
}
else
{
cout << "Rhetorician was not found!";
}
}
// Method for sorting nodes
void DlinkedList::sort()
{
int count = this->getLenght();
Node *tmp, *current;
int i, j;
for (i = 1; i < count; i++)
{
current = this->head;
for (j = 0; j <= count - i - 1; j++)
{
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient)
{
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
current->next = after->next;
current->prev = after;
after->next = current;
after->prev = before;
}
tmp = current;
current = current->next;
}
}
}
// List destructor
DlinkedList::~DlinkedList()
{
Node *next_node = NULL;
for (Node *node_cur = this->head; node_cur != NULL; node_cur = next_node)
{
next_node = node_cur->next;
delete node_cur->rhetorician;
delete node_cur;
}
this->head = NULL;
this->length = 0;
}
Main:
#include <iostream>
#include "DlinkedList.h"
#include <fstream>
#include <vector>
#include <sstream>
// Namespace
using namespace std;
// Parser of line to vector array
vector<string> split(string strToSplit, char delimeter)
{
stringstream ss(strToSplit);
string item;
vector<string> splittedStrings;
while (getline(ss, item, delimeter))
{
splittedStrings.push_back(item);
}
return splittedStrings;
}
// File loader
void read_file(const char *name, DlinkedList *list)
{
// Variable for loading line
string line;
{
// Create relation
ifstream file(name);
// Check if file exists
if (file)
{
// Check if file is empty
if (!(file.peek() == ifstream::traits_type::eof()))
{
// Read data from file and put into LinkedList
while (getline(file, line)) {
list->appendNode(new Rhetorician(split(line, ';')[0], split(line, ';')[1],
split(line, ';')[2], stoi(split(line, ';')[3])));
}
}
// Close file
file.close();
}
}
}
// Main method
int main()
{
// Create instance of doubly linked list
DlinkedList *list = new DlinkedList();
// Read file and push data into list
read_file("seznam_enumat.txt", list);
// Print all loaded rhetoricians behind added own one
cout << "\nAll rhetoricians from file:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Append other rhetoricians
list->appendNode(new Rhetorician("Cain", "Foster", "Structural and molecular virology", 7));
list->appendNode(new Rhetorician("Stacy", "Algar", "Dept of microbiology and immunology", 5));
list->appendNode(new Rhetorician("Oded", "Philander", "Experimental plasma physics", 3));
list->appendNode(new Rhetorician("Shay", "Rimon", "Experimental plasma physics", 10));
// Sort rhetoricians in list
list->sort();
// Delete rhetorician by name
//list->remove("Stacy");
// Finder of rhetorician
cout << "\nFound rhetorician:" << endl;
cout << "##################################################################################################\n" << endl;
list->find("Shay");
// Print all sorted rhetoricians
cout << "\nAll rhetoricians:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Destruct list
delete list;
// Check if user click any key
getchar();
return 0;
}
Rhetorician:
#include "Rhetorician.h"
Rhetorician::Rhetorician(string name, string surname, string contribution, int coefficient)
{
this->name = name;
this->surname = surname;
this->contribution = contribution;
this->coefficient = coefficient;
}
void Rhetorician::printer()
{
// Name
cout << "Name:" << endl;
cout << this->name << endl;
// Surname
cout << "Surname:" << endl;
cout << this->surname << endl;
// Contribution
cout << "Contribution:" << endl;
cout << this->contribution << endl;
// Coefficient
cout << "Coefficient:" << endl;
cout << this->coefficient << endl;
}
The main issue is in sort(). It is not handling the pointers correctly.
Take a short example, 3 -> 2 -> 1 and you will get it.
Here is the corrected code with unnecessary variables removed:
void DlinkedList::sort() {
int count = this->getLenght();
Node *current;
int i, j;
for (i = 1; i < count; i++) {
current = this->head;
for (j = 0; j <= count - i - 1; j++) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
before = current->prev;
after = current->next;
if (before != nullptr) {
before->next = after;
} else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != nullptr) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
} else {
current = current->next; // Go to next node only if current->rhetorician->coefficient > current->next->rhetorician->coefficient condition is false.
}
}
}
}
The upwardly sorted list is working super but when I tried to sort the list downwardly only change the character > for < it is not working. Must be changed before node and after node?
// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}

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.

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!

Writing and Printing an extra 0 to sorted files and cutting node (singly linked list)off the end C++

That may seem kind of vague so really sorry. I am writing to a file and printing to a console the sorted nodes in this singly linked list. Unfortunately, in the sort list, it both prints and writes an extra 0 at the front and cuts a value off the end. Here is the code:
void SLLIntStorage::Read(istream& r)
{
char c[13];
r >> c;
r >> numberOfInts;
head = new Node;
head->next = NULL;
tail = head;
r >> head->data;
for (int i = 0; i < numberOfInts; i++)
{
Node* newNode = new Node;
r >> newNode->data;
if(_sortRead)
{
if(newNode->data > tail->data)
{
tail->next = newNode;
tail = newNode;
}
else if(head->data > newNode->data)
{
newNode->next = head;
head = newNode;
}
else
{
current = head;
while(current->next != NULL)
{
if(current->next->data > newNode->data)
{
newNode->next = current->next;
current->next = newNode;
break;
}
else
{
current = current->next;
}
}
}
}
else
{
tail->next = newNode;
tail = newNode;
}
}
print();
}
void SLLIntStorage::Write(ostream& w)
{
current = head;
for(int i = 0; i < numberOfInts; i++)
{
w << current->data << endl;
if (current->next != NULL)
current = current->next;
}
}
void SLLIntStorage::print()
{
current = head;
for(int i = 0; i < numberOfInts; i++)
{
cout << current->data << endl;
//system("pause");
if(current->next != NULL)
{
current = current->next;
}
}
}
File sample:
0
0
1
2
2
3
........
9995
9996
9996
9998
//supposed to be another 9998 here
It seems you read one entry too much. You first read an entry in the line r >> head->data;
just before the for-loop. Then you read an additional numberOfInts entries in the for-loop for a total of numberOfInts+1 entries.