C++ linked list doesn stop growing [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to write a function that calculates the N-th Fibonacci number using doubly linked lists, but for some reason when I compile and run the linked list does not stop growing, it keeps adding 1 number over and over with no ending.
This should be a SSCCE:
#include <iostream>
using namespace std;
class node {
public:
int value;
node* previous;
node* next;
};//node
class number {
public:
node* start;
node* end;
node* add (int value);
void show (int K);
number ();
void destroy ();
void copy (number gg1);
void addition (number gg1, number gg2, int K);
void fibonacci (int K, int times);
};//number
number::number () {
start = NULL;
end = NULL;
}
int power (int K) {
int L = 1;
for (int i = (K-1); i > 0; i--) {
L = L*10;
}
return L;
}
int checksize (int value) {
int counter = 0;
while (value != 0) {
value = value / 10;
counter += 1;
}
return counter;
}
void number::show (int K) {
node* current;
cout << "\nValue:" << endl;
if (start == NULL) {
cout << "\nNothing\n" << endl;
}
if (start != NULL) {
current = start;
while (current != NULL) {
if (current->value == 0) {
for (int i = 0; i < K; i++) {
cout << "0";
}
cout << "\n";
}
else {
int size = checksize (current->value);
for (int j = size; j < K; j++) {
cout << "0";
}
cout << current->value << endl;
}
current = current->next;
}
}
//cout << "\n";
}
int main () {
number gg1;
number gg2;
number gg3;
const int K = 5;
gg1.fibonacci (K, 10);
}
node* number::add(int value) {
node* currentcode;
if (start == NULL){
currentcode = new node;
start = currentcode;
end = currentcode;
currentcode->next = NULL;
currentcode->previous = NULL;
currentcode->value = value;
return currentcode;
}
if (start != NULL) {
currentcode = new node;
currentcode->next = NULL;
end->next = currentcode;
currentcode->previous = end;
end = currentcode;
currentcode->value = value;
return currentcode;
}
return NULL;
}
void number::addition (number gg1, number gg2, int K) {
int value1, value2, value3;
int carry = 0;
node* current1;
node* current2;
current1 = gg1.start;
current2 = gg2.start;
while (current1 != NULL || current2 != NULL) {
if (current1 != NULL && current2 !=NULL) {
value1 = current1->value;
value2 = current2->value;
value3 = value1 + value2 + carry;
current1 = current1->next;
current2 = current2->next;
}
else if (current1 == NULL && current2 != NULL) {
value3 = current2->value + carry;
current2 = current2->next;
}
else if (current1 != NULL && current2 == NULL) {
value3 = current1->value + carry;
current1 = current1->next;
}
checksize(value3);
if (value3 > power(K)) {
value3 = value3 - 10*(power(K));
carry = 1;
}
else
carry = 0;
add(value3);
if ((current1 == NULL && current2 == NULL) && (carry == 1))
add(1);
}
}
void number::destroy () {
node* current;
node* current2;
if (start != NULL) {
current = start;
current2 = current->next;
while (current2 != NULL) {
delete current;
current = current2;
current2 = current->next;
}
delete current;
}
}
void number::fibonacci (int K, int times) {
number g1;
number g2;
number g3;
destroy ();
g1.add (1);
g2.add (1);
g3.addition (g1, g2, K);
g2.copy(g1);
g1.show(K);
g2.show(K);
//g1.copy(g3);
//g1.show(K);
//g2.show(K);
//g3.show(K);
//g3.addition (g1, g2, K);
//g3.show(K);
//g2.copy(g1);
//g1.copy(g3);
/*for (int i = 0; i < 2; i++) {
g3.addition (g1, g2, K);
g3.show(K);
g2.copy(g1);
g1.copy(g3);
}*/
copy(g3);
}
void number::copy (number gg1) {
int value;
destroy ();
node* current = gg1.start;
while (current != NULL) {
value = current->value;
add(value);
current = current->next;
}
}
Whenever I run the Fibonacci function it gives me endless 1's in the terminal.
The number class is just a basic doubly linked pointer list.
The addition function standalone works just fine, so does the copy. In fact everything was working fine until this. It's easy to finish the function with a for-loop, but this error prevents me from doing so. Does anyone know what my mistake is? Thanks in advance.

Right now, you have invalid memory access, since calling delete on each node in destroy() does not NULL-out the memory but it only marks the memory free.
Suggested correction:
void number::destroy () {
node* current;
node* current2;
if (start != NULL) {
current = start;
current2 = current->next;
while (current2 != NULL) {
delete current;
current = current2;
current2 = current->next;
}
delete current;
}
start = NULL; // so you can't access the now non-existing list anymore.
end = NULL;
}
Remark:
Class names should be capital-first by widely adapted convention.
You should not pass a class by value in your copy and addition function but const-ref.
Better use in this case operator= instead of copy. copy can be copy_from or copy_to, calling a function copy is ambigous, really.
Always better to use for loops when you can.
Node is not a class but a struct, it is better to call it a struct.
The new code can also look like this:
Number& Number::operator=(const Number& n)
{
destroy();
for(Node* current = gg1.start; current; current = current->next)
add(current->value);
}
void Number::destroy()
{
Node* temp;
for(Node* current = start; current; current = current->next, delete temp)
temp = current;
start = NULL;
end = NULL;
}

Related

C++ binary max heap Read Access Violation

So I'm making a binary max heap for my c++ class and I keep encountering this exception saying that I'm returning a nullptr in my class methods. I'm having trouble finding where it could be at in my code so any help would be greatly appreciated. The exception that keeps getting thrown is as follows:
Unhandled exception thrown: read access violation.
**std::_String_alloc<std::_String_base_types<char,std::allocator<char> > ::_Get_data**(...) returned nullptr. occurred
Here's my header file for the tree:
#ifndef HEAP_H
#define HEAP_H
#include <iostream>
#include "THeapNode.h"
class TreeHeap {
private:
THeapNode *root; // the top node of the heap
int next_loc; // the next valid location to place a node
void bubble_up(THeapNode *node); //performs the bubble up operation on the given node
void bubble_down(THeapNode *node); //performs the bubble down operation on the given node
void clear_heap(THeapNode *node); // removes all elements from the heap
public:
TreeHeap(); // the constructor
~TreeHeap(); // the destructor
THeapNode* find_node(const int position); // finds the node in the position given and returns a pointer to it
void insert(const string &item); // creates a node with the string given as the value and places it in the next location
bool Delete(); // removes the root of the heap and returns false if the tree is empty
};
#endif
Here's my Node's .h file:
#ifndef NODE_H
#define NODE_H
#include<string>
using std::string;
struct THeapNode {
string data; // stores a data string
THeapNode *parent; // a pointer to the parent node
THeapNode *rightChild; // a pointer to the right child node
THeapNode *leftChild; // a pointer to the left child node
THeapNode( const string &str );
};
#endif
And here's my .cpp file:
#include "stdafx.h"
#include <cmath>
#include "TreeHeap.h"
#include "THeapNode.h"
TreeHeap::TreeHeap() {
root = NULL;
next_loc = 1;
};
TreeHeap::~TreeHeap() {
THeapNode *current = root;
THeapNode *deleteNode = NULL;
int d = floor(log2(next_loc - 1));
int j = next_loc;
for ( int i = 1; i <= j-1; i++ ) {
while (1) {
int d = floor(log2(next_loc - i));
int power = std::pow(2, d - 1);
if (next_loc == 1) {
deleteNode = current;
j -= 1;
}
else if (next_loc < (std::pow(2, d - 1) * 3)) {
current = current->leftChild;
}
else {
current = current->rightChild;
}
// Update location and depth to reflect traversal
next_loc = std::pow(2, d - 1) + next_loc % power;
d = d - 1;
}
clear_heap(deleteNode);
}
}
void TreeHeap::clear_heap(THeapNode *node) {
if (node == NULL) {
return;
}
node->data = "";
node->leftChild = NULL;
node->rightChild = NULL;
node->parent = NULL;
}
void TreeHeap::insert( const string &value ) {
THeapNode newNode = THeapNode(value);
int loc = next_loc;
if (loc == 1) {
*root = newNode;
}
THeapNode *current = root;
while (1) {
int d = floor(log2(loc));
int power = std::pow(2, d - 1);
if (loc < (power * 3)) {
if (current->leftChild = nullptr) {
*current->leftChild = newNode;
newNode.parent = current;
next_loc += 1;
break;
}
else {
current = current->leftChild;
}
}
else {
if (current->rightChild = nullptr) {
*current->rightChild = newNode;
newNode.parent = current;
next_loc = +1;
break;
}
else {
current = current->rightChild;
}
}
// Update location and depth to reflect traversal
loc = std::pow(2, d - 1) + loc % power;
d = d - 1;
}
std::cout << current->data << "\n";
system("PAUSE");
}
void TreeHeap::bubble_up( THeapNode *node ) {
if (node == NULL) {
return;
}
THeapNode *parent = node->parent;
while ( parent->data < node->data ) {
parent = node->parent;
string temp = parent->data;
parent->data = node->data;
node->data = temp;
}
}
void TreeHeap::bubble_down( THeapNode *node ) {
if (node == NULL) {
return;
}
while( node->data < node->rightChild->data || node->data < node->leftChild->data ){
if (node->rightChild->data > node->leftChild->data) {
THeapNode *right = node->rightChild;
string temp = right->data;
right->data = node->data;
node->data = temp;
}
else if (node->rightChild->data < node->leftChild->data) {
THeapNode *left = node->leftChild;
string temp = left->data;
left->data = node->data;
node->data = temp;
}
}
}
THeapNode* TreeHeap::find_node( const int position ){
int loc = position;
int d = floor(log2(position));
int power = std::pow(2, d - 1);
THeapNode *returnValue = root;
while (returnValue != NULL && 1 < position && position < (next_loc - 1)) {
if (loc == 1) {
return returnValue;
}
else if (loc < ( std::pow( 2, d-1 ) * 3)) {
returnValue = returnValue->leftChild;
}
else {
returnValue = returnValue->rightChild;
}
// Update location and depth to reflect traversal
loc = std::pow(2, d - 1) + loc % power;
d = d - 1;
}
std::cout << returnValue->data<<"\n";
return returnValue;
}
bool TreeHeap::Delete() {
if (next_loc = 1) {
return false;
}
int d = floor(log2(next_loc - 1));
THeapNode *current = root;
THeapNode *usedNode = NULL;
int loc = next_loc - 1;
while ( 1 ) {
int d = floor(log2(loc));
int power = std::pow(2, d - 1);
if (loc == 1) {
usedNode = current;
break;
}
else if (loc < (std::pow(2, d - 1) * 3)) {
current = current->leftChild;
}
else {
current = current->rightChild;
}
// Update location and depth to reflect traversal
loc = std::pow(2, d - 1) + loc % power;
d = d - 1;
}
THeapNode *temp = root;
clear_heap(root);
root = usedNode;
delete temp;
bubble_down(root);
return true;
}
Thanks in advance for any help you've got.
Quick inspection reveals errors in your bubble_up and bubble_down functions.
In bubble_up, you have the following:
THeapNode *parent = node->parent;
while ( parent->data < node->data ) {
parent = node->parent;
string temp = parent->data;
parent->data = node->data;
node->data = temp;
}
This is going to fail when a node bubbles all the way to the top, because it doesn't check for the node being at the root. You need to write:
while (parent != NULL && parent->data < node->data)
In bubble_down, you have this code:
while( node->data < node->rightChild->data || node->data < node->leftChild->data ){
if (node->rightChild->data > node->leftChild->data) {
You don't check to see if the rightChild or leftChild are NULL.
More importantly, that looks like an infinite loop to me because you never change the value of node.
Those are just the errors I saw on a quick read through your code. There might be more.

I have a program that works for whole numbers, but I need to get it to work for decimal numbers as well

So my assignment requires us to use doubly linked lists to add or multiply numbers together and print them out. I was able to get it to work for whole numbers, but I can't figure out what to change to make it work for decimal numbers as well. Here's what I've got so far. I know it's not the most efficient or cleanest code, but I can try to clarify stuff if it doesn't make sense to you
For example this program will work fine if I do 50382+9281 or 482891*29734,but I need to get it to work for something like 4.9171+49.2917 or 423.135*59
EDIT: Pretend the int values are doubles. I changed it on my actual code, but the result when I do the math is still giving me a whole number so I need to figure out how to insert the decimal at the right place
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
using namespace std;
// A recursive program to add two linked lists
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <string.h>
// A linked List Node
struct node
{
int data;
node* next;
node *prev;
};
typedef struct node node;
class LinkedList{
// public member
public:
// constructor
LinkedList(){
int length = 0;
head = NULL; // set head to NULL
node *n = new node;
n->data = -1;
n->prev = NULL;
head = n;
tail = n;
}
// This prepends a new value at the beginning of the list
void addValue(int val){
node *n = new node(); // create new Node
n->data = val; // set value
n->prev = tail; // make the node point to the next node.
// head->next = n;
// head = n;
// tail->next = n; // If the list is empty, this is NULL, so the end of the list --> OK
tail = n; // last but not least, make the head point at the new node.
}
void PrintForward(){
node* temp = head;
while(temp->next != NULL){
cout << temp->data;
temp = temp->next;
}
cout << '\n';
}
void PrintReverse(){
node* temp = tail;
while(temp->prev != NULL){
cout << temp->data;
temp = temp->prev;
}
cout << '\n';
}
void PrintReverse(node* in){
node* temp = in;
if(temp->prev== NULL){
if(temp->data == -1)
cout << temp->data << '\n';
}
else{
cout << temp->data << '\n';
temp = temp->prev;
PrintReverse(temp);
}
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
node *n = head;
int ret = n->data;
head = head->next;
delete n;
return ret;
}
void swapN(node** a, node**b){
node*t = *a;
*a = *b;
*b = t;
}
node *head;
node *tail;
// Node *n;
};
/* A utility function to insert a node at the beginning of linked list */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A utility function to print linked list */
void printList(struct node *node)
{
while (node != NULL)
{
printf("%d", node->data);
node = node->next;
}
// printf("\n");
}
// A utility function to swap two pointers
void swapPointer( node** a, node** b )
{
node* t = *a;
*a = *b;
*b = t;
}
/* A utility function to get size of linked list */
int getSize(struct node *node)
{
int size = 0;
while (node != NULL)
{
node = node->next;
size++;
}
return size;
}
// Adds two linked lists of same size represented by head1 and head2 and returns
// head of the resultant linked list. Carry is propagated while returning from
// the recursion
node* addSameSize(node* head1, node* head2, int* carry)
{
// Since the function assumes linked lists are of same size,
// check any of the two head pointers
if (head1 == NULL)
return NULL;
int sum;
// Allocate memory for sum node of current two nodes
node* result = (node *)malloc(sizeof(node));
// Recursively add remaining nodes and get the carry
result->next = addSameSize(head1->next, head2->next, carry);
// add digits of current nodes and propagated carry
sum = head1->data + head2->data + *carry;
*carry = sum / 10;
sum = sum % 10;
// Assigne the sum to current node of resultant list
result->data = sum;
return result;
}
// This function is called after the smaller list is added to the bigger
// lists's sublist of same size. Once the right sublist is added, the carry
// must be added toe left side of larger list to get the final result.
void addCarryToRemaining(node* head1, node* cur, int* carry, node** result)
{
int sum;
// If diff. number of nodes are not traversed, add carry
if (head1 != cur)
{
addCarryToRemaining(head1->next, cur, carry, result);
sum = head1->data + *carry;
*carry = sum/10;
sum %= 10;
// add this node to the front of the result
push(result, sum);
}
}
// The main function that adds two linked lists represented by head1 and head2.
// The sum of two lists is stored in a list referred by result
void addList(node* head1, node* head2, node** result)
{
node *cur;
// first list is empty
if (head1 == NULL)
{
*result = head2;
return;
}
// second list is empty
else if (head2 == NULL)
{
*result = head1;
return;
}
int size1 = getSize(head1);
int size2 = getSize(head2) ;
int carry = 0;
// Add same size lists
if (size1 == size2)
*result = addSameSize(head1, head2, &carry);
else
{
int diff = abs(size1 - size2);
// First list should always be larger than second list.
// If not, swap pointers
if (size1 < size2)
swapPointer(&head1, &head2);
// move diff. number of nodes in first list
for (cur = head1; diff--; cur = cur->next);
// get addition of same size lists
*result = addSameSize(cur, head2, &carry);
// get addition of remaining first list and carry
addCarryToRemaining(head1, cur, &carry, result);
}
// if some carry is still there, add a new node to the fron of
// the result list. e.g. 999 and 87
if (carry)
push(result, carry);
}
node* reverse_list(node *m)
{
node *next = NULL;
node *p = m;
node *prev;
while (p != NULL) {
prev = p->prev;
p->prev = next;
next = p;
p = prev;
}
return prev;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Multiply2(node* n1, node* n2);
int digitsPerNode = 2;
node* result;
node* resultp = result;
node* resultp2 = result;
void Multiply(node* n1, node* n2)
{
if (n2->prev != NULL)
{
Multiply(n1, n2->prev);
}
Multiply2(n1, n2);
resultp2 = resultp = resultp->prev;
}
void Multiply2(node* n1, node* n2)
{
if (n1->prev != NULL)
{
Multiply2(n1->prev, n2);
}
if (resultp2 == NULL)
{
resultp2->data = 0;
result = resultp = resultp2;
}
int m = n1->data * n2->data + resultp2->data;
int carryon = (int)(m / pow(10, digitsPerNode));
resultp2->data = m % (int)pow(10, digitsPerNode);
if (carryon > 0)
{
if (resultp2->prev == NULL)
{
resultp2->prev->data = carryon;
}
else
{
resultp2->prev->data += carryon;
}
}
resultp2 = resultp2->prev;
}
/* int* buffer;
int lenBuffer = 0;
void multiplyHelper(int v, node* , int o);
void addToBuffer(int v, int i);
node* multiply(node* num1, node* num2)
{
if (num1 == NULL || num2 == NULL) return NULL;
int length1 = getSize(num1);
int length2 = getSize(num2);
if (length1 > length2) return multiply(num2, num1);
// initialize buffer
lenBuffer = length1 + length2;
buffer = new int[lenBuffer];
memset(buffer, 0, sizeof(int) * lenBuffer);
// multiply
int offset = 0;
node* anode = num1;
while (anode && anode->data!= -1)
{
multiplyHelper(anode->data, num2, offset);
anode = anode->prev;
offset++;
}
// transfer buffer to a linked list
node* h;
int pos = 0;
while (pos < lenBuffer && buffer[pos] == 0) pos++;
if (pos < lenBuffer)
{
node* temp;
temp->data = buffer[pos++];
h = temp;
anode = h;
while (pos < lenBuffer)
{
node* temp;
temp->data = buffer[pos++];
anode->prev = temp;
anode = anode->prev;
}
}
delete buffer;
lenBuffer = 0;
buffer = NULL;
cout << h->data << endl;
return h;
}
// multiply a single digit with a number
// called by multiply()
void multiplyHelper(int value, node* head, int offset)
{
// assert(value >= 0 && value <= 9 && head != NULL);
if (value == 0) return;
node* anode = head;
int pos = 0;
while (anode != NULL)
{
int temp = value * anode->data;
int ones = temp % 10;
if (ones != 0) addToBuffer(ones, offset + pos + 1);
int tens = temp / 10;
if (tens != 0) addToBuffer(tens, offset + pos);
anode = anode->prev;
cout << anode->data;
pos++;
}
}
// add a single digit to the buffer at place of index
// called by multiplyHelper()
void addToBuffer(int value, int index)
{
// assert(value >= 0 && value <= 9);
while (value > 0 && index >= 0)
{
int temp = buffer[index] + value;
buffer[index] = temp % 10;
value = temp / 10;
index--;
}
}*/
// Driver program to test above functions
int main(int argc, char *argv[])
{
char filename[50];
string name= argv[1];
string dig;
name.erase(0,9);//Parse input to only get input file.
ifstream file;
int digits;
for(int i = 0; i < name.length(); i++){
if(name.at(i) == ';'){
// dig = name.substr(0,name.length()-i);
name = name.substr(0,name.length()-i);
}
}
//cout << dig << endl;
//file.open("input.txt");
file.open(name.c_str());
digits = 2;
///////
///////////////////////////////////////////////////////////////////////
int words = 0;
int numbers = 0;
while(!file.eof()) //Goes through whole file until no more entries to input
{
string word;
getline(file,word); //Inputs next element as a string
// word << file;
//cout << word << '\n';
int x = 0;
node *head1 = NULL, *head2 = NULL, *result = NULL;
int counter = 0;
int t1index = 0; //keep tracks of nodes to multiply
int t2index = 0;
char operatorX;
LinkedList tempList1;
LinkedList tempList2;
while(x<word.length()) //Loops through each string input
{
//if(x<word.length()&&isalpha(word.at(x))) //Checks that x is in bounds and that char at position x is a letter
if(x<word.length()&&isdigit(word.at(x))) //Checks that x is in bounds and that char at position x is a number/digit
{
int start = x;
while(x<word.length()&&isdigit(word.at(x))) //Loops past the number portion
{
x++;
}
string temp = word.substr(start, x).c_str();
// cout << temp << '\n';
for(int i = 0; i < temp.length();i++){
tempList1.addValue(atoi(temp.substr(i, 1).c_str()));
// push(&head1, atoi(temp.substr(i, 1).c_str()));
counter++;
t1index++;
}
//search for the operator
while(x<word.length()){
if(x<word.length()&& (!isspace(word.at(x)) && !isdigit(word.at(x))))
{
while(x<word.length()&&(!isspace(word.at(x)) && !isdigit(word.at(x)))) //Loops past the letter portion
{
// cout << (word.at(x))<< '\n';
operatorX = word.at(x);
x++;
}
//search second value
while(x<word.length()){ //second value find
//start
if(x<word.length()&&isdigit(word.at(x))) //Checks that x is in bounds and that char at position x is a number/digit
{
int start = x;
while(x<word.length()&&isdigit(word.at(x))) //Loops past the number portion
{
x++;
}
string temp = word.substr(start, x).c_str();
for(int i = 0; i < temp.length();i++){
tempList2.addValue(atoi(temp.substr(i, 1).c_str()));
// push(&head2, atoi(temp.substr(i, 1).c_str()));
// cout << atoi(temp.substr(i, 1).c_str());
counter++;
}
//////START READING NUMBERS BACKWARDS
LinkedList finalList;
node* tempA = tempList1.tail;
node* tempB = tempList2.tail;
// multiply(tempA, tempB);
//ADDITION
while(tempA != NULL){
if(tempA->data != -1){
push(&head1,tempA->data);
// cout << tempA->data;
}
tempA = tempA->prev;
}
while(tempB != NULL){
if(tempB->data != -1){
push(&head2, tempB->data);
// cout << tempB->data;
}
tempB = tempB->prev;
}
// multiply(head1, head2);
// result = multiply(head1, head2);
// tempList1.PrintReverse();
addList(head1, head2, &result);
printList(head1);
cout << operatorX;
printList(head2);
cout << "=";
printList(result);
cout << endl;
}
else{
x++;
}
//end
}
}
else{
x++;
}
}
}
else //If char at position x is neither number or letter skip over it
{
x++;
}
}
}
}
Since you're working in C++, use a template/overloaded operators. Cast your ints to a floating point type as necessary. See e.g.:
C++ Template problem adding two data types

C++ linked list implementation segmentation fault (core dumped) error

I am currently trying to learn C++ on my own and have been going through some textbooks and trying to do some problems. While learning pointers, I decided to try and implement a linked list on my own. I have written the program, but keep getting an error that says: "segmentation error (core dumped)". I have searched through other similar questions on this website and although there are a lot on the same topic, none have helped me fix my problem. I'm pretty new to programming and pointers, so any help will be appreciated!
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node
{
int element;
struct node *next;
}*start;
class pointerlist
{
public:
node* CREATE(int num);
void ADD(int num);
int FIRST();
int END();
int RETRIEVE(int pos);
int LOCATE(int num);
int NEXT(int pos);
int PREVIOUS(int pos);
void INSERT(int pos, int num);
void DELETE(int pos);
void MAKENULL();
pointerlist()
{
start = NULL;
}
};
main()
{
pointerlist pl;
start = NULL;
pl.ADD(1);
cout << "Added 1" << endl;
for (int j=1; j<=5; j++)
pl.ADD(j);
cout << "The pointer implemented list is: " << endl;
for (int i=1; i<=5; i++)
{
cout << pl.END() << " " ;
}
cout << endl << endl;
}
void pointerlist::ADD(int num)
{
struct node *temp, *s;
temp = CREATE(num);
s = start;
while (s->next != NULL)
s = s->next;
temp->next = NULL;
s->next = temp;
}
node *pointerlist::CREATE(int num)
{
struct node *temp, *s;
temp = new(struct node);
temp->element = num;
temp->next = NULL;
return temp;
}
int pointerlist::FIRST ()
{
int num;
struct node *s;
s = start;
num = s->element;
return num;
}
int pointerlist::END()
{
struct node *s;
s = start;
int num;
while (s != NULL);
{
num = s->element;
s = s->next;
}
return num;
}
int pointerlist::RETRIEVE(int pos)
{
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
{
return s->element;
}
s = s->next;
}
}
int pointerlist::LOCATE(int num)
{
int pos = 0;
bool flag = false;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->element == num)
{
flag == true;
return pos;
}
s = s->next;
}
if (!flag)
return -1;
}
int pointerlist::NEXT(int pos)
{
int next;
int counter = 0;
struct node *s;
s = start;
while (s != NULL)
{
counter++;
if (counter == pos)
break;
s = s->next;
}
s = s->next;
next = s->element;
return next;
}
int pointerlist::PREVIOUS(int pos)
{
int previous;
int counter = 1;
struct node *s;
s = start;
while (s != NULL)
{
previous = s->element;
counter++;
if (counter = pos)
break;
s = s->next;
}
return previous;
}
void pointerlist::INSERT(int pos, int num)
{
struct node *temp, *s, *ptr;
temp = CREATE(num);
int i;
int counter = 0;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start = NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if(pos>1 && pos <= counter)
{
s = start;
for (i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
}
void pointerlist::DELETE(int pos)
{
int counter;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos >0 && pos <= counter)
{
s = start;
for(int i=1; i<pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
free(s);
}
}
void pointerlist::MAKENULL()
{
free(start);
}
The problem occurs in line 39 of my code (inside main where I write pl.ADD(1)). In this line I was trying to start off the list with the vale 1. There maybe be problems with the rest of my code too, but I have not been able to get past this line to check. Please help!
List is empty at the beginning, therefore it will fail on s-> next as s == start ==NULL :
s = start;
while (s->next != NULL)
Thanks for the help! I was able to fix the problem by adding a first function which adds the first element to the list. But now I am having trouble with my END function. It appears to not be entering the loop within the function when it is called. I cannot find a reason for this. Would anyone be able to help me figure out why my END function does not work?

Error on my Linked List code, can anybody help me to check where is wrong?

Here is a small Linked List challenge from my class that we need to define a function
void restoreSorted(intListEntry * &)
where intListEntry is a struct
struct intListEntry {
int i; // The int value we want to store in this entry
intListEntry *next; // Address of the next entry in the list
};
The argument is the head of a linked list of integers that sorted in non-decreasing order except for one entry, which is out of place. The function should restore the list to sorted non-decreasing. For example, given as argument; head --> -12 --> -12 --> 0 --> -1 --> 12 --> 122, up on return from restoreSorted(), the list should be: head --> -12 --> -12 --> -1 --> 0 --> 12 --> 122.
and here is my code:
void restoreSorted(intListEntry * &root) {
intListEntry *conductor = root;
intListEntry *checker;
while (conductor->next != NULL) {
if (conductor->i > conductor->next->i) { //detect which one is out of place
checker = conductor;
intListEntry *checker2 = conductor->next;
int temp;
while (checker->i > checker2->i) {
temp = checker->i; //start of swapping value
checker->i = checker2->i; //until it is in the right order
checker2->i = temp;
checker = checker2;
checker2 = checker2->next;
}
break;
}
conductor = conductor->next;
}
However, there are five test cases, and I only pass one of them. I check it over and over again I still cannot find any bug in my code.
With the help of the those comments, I finally debug my code and make two versions using different approach.
The first one is using my original method - bubble sort:
void restoreSorted( intListEntry * &root ){
int length = 0;
intListEntry *current = root;
intListEntry *prev = NULL;
int t = 0;
while (current != NULL){
length++;
prev = current;
current = current -> next;
}
current = root;
prev = NULL;
for (int i = 0; i < length; i++){
for (int j = 0; j < length-1 ; j++){
if (prev == NULL){
prev = current;
current = current->next;
}
if (current->i < prev->i){
t = prev->i;
prev->i = current->i;
current->i = t;
current = current->next;
} else {
prev = current;
current = current->next;
}
if (current == NULL) break;
}
current = root;
prev = NULL;
}
}
The second one is using insertion method:
void restoreSorted(intListEntry * &root) {
intListEntry *conductor = root;
intListEntry *behind = root;
intListEntry *checker;
if (conductor != NULL || conductor->next != NULL) {
while (conductor->next != NULL) {
if (conductor->i > conductor->next->i) {
checker = conductor;
intListEntry *checker2 = conductor;
if (checker2->next->next == NULL) {
int temp = checker->i;
checker->i = checker2->next->i;
checker2->next->i = temp;
break;
} else {
while (checker->i > checker2->next->i && checker2->next != NULL) {
checker2 = checker2->next;
}
if (checker->i > checker2->i && checker2->next == NULL) {
behind->next = checker->next;
checker2->next = checker;
checker->next = NULL;
} else if (checker->i < checker2->next->i) {
behind->next = checker->next;
conductor = checker2->next;
checker2->next = checker;
checker->next = conductor;
break;
}
}
}
behind = conductor;
conductor = conductor->next;
}
}
}

A count function that counts the leaf nodes of a height balanced tree

I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput