I have to make two types of list data types for my data structures class, an ArrayList and a Linkedlist. The ArrayList will be based on arrays and the LinkedList will be based on nodes, then i need to compare their performance on adding (on the desired position), updating and removing elements from front, end and middle of the list for lists with 100,1000 and 10000 elements. The point of the homework is to show that linked lists are faster. I made both structures and all the functions but when i test them the result always shows that my array lists are faster. Can someone please tell me why my linked lists works slower?
struct ArrayList {
int* head;
int size;
void build();
void add(int, int);
void update(int, int);
void remove(int);
void print();
void clear();
};
struct Node {
int data;
Node* next;
};
struct LinkedList {
Node* head;
int size;
void build();
void add(int, int);
void update(int, int);
void remove(int);
void print();
void clear();
};
void LinkedList::build() {
head = NULL;
size = 0;
}
void LinkedList::add(int index, int value) {
Node* n = new Node();
n->data = value;
if (head == NULL) { // adding to an empty list
head = n;
size++;
}
else {
if (index == 0) { // adding at front
n->next = head;
head = n;
size++;
}
else if (index < size) { // adding inside
Node* p = head;
int c = 1;
while (c < index) {
p = p->next;
c++;
}
n->next = p->next;
p->next = n;
size++;
}
else if (index == size) { // adding at the end
Node* p = head;
while (p->next) {
p = p->next;
}
p->next = n;
size++;
}
else {
cout << "index out of range";
}
}
}
void ArrayList::build() {
size = 0;
head = new int[size];
}
void ArrayList::add(int index, int value) {
int* arr = new int[size + 1];
if (index == size) { //adding at the end
for (int i = 0; i < size; i++) {
arr[i] = head[i];
}
arr[size] = value;
delete head;
head = arr;
size++;
}
else if (index < size) { //adding inside or front
for (int i = 0; i < index; i++) {
arr[i] = head[i];
}
arr[index] = value;
for (int i = index; i < size; i++) {
arr[i + 1] = head[i];
}
delete head;
head = arr;
size++;
}
else {
cout << "index out of range.";
}
}
Testing code
ArrayList* a = new ArrayList();
LinkedList* l = new LinkedList();
l->build();
a->build();
int n = 10000;
for (int i = 0; i < n; i++) {
l->add(i, i);
a->add(i, i);
}
auto begin = std::chrono::high_resolution_clock::now();
a->add(n, 1);
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
auto begin2 = std::chrono::high_resolution_clock::now();
l->add(n, 1);
auto end2 = std::chrono::high_resolution_clock::now();
auto elapsed2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - begin2);
cout << "with " << n << " " << "elements" << endl;
cout << endl;
cout << "ArrayList adding time: " << elapsed.count() << " nano-seconds" << endl;
cout << endl;
cout << "LinkedList adding time: " << elapsed2.count() << " nano-seconds" << endl;
Related
I am trying to implement a simple open hash in c++ for the sake of learning. I am getting very confused about the interaction of functions with array pointers, and I am at the end of my wits.
The code:
struct node{
int data;
node* next;
node* prev;
bool state;
node(){
prev = next = NULL;
state = true;
}
};
//state true means empty, state false means full.
void insert(node *array,int value){
node *current = array;
if(array->state == true){
array->data = value;
array->state = false;
} else {
node* add = new node();
add->data = value;
add->state = false;
while(current->next != NULL){
current = current->next;
}
current->next = add;
add->prev = current;
}
}
void display(node *array, int size){
node *show = new node();
for(int i = 0; i< size; i++){
if(array->state == false){
cout<<array->data;
show = array;
while(show->next != NULL){
show = show->next;
cout<<" --> "<<show->data;
}
} else {
cout<<"Empty.";
}
cout<<"\n\n";
}
}
int main(){
int size;
cout<<"Enter size of the hash table: ";
cin>>size;
node *array = new node[size];
int value;
cout<<"Enter Value: ";
cin>>value;
int index = value%size;
//inserting single value
insert(&array[index],value);
//Hash table output.
display(array,size);
return 0;
}
When I run this code, instead of showing "empty" in places where the array's state is empty, it seems as if the entire array has the same value. The problem lies in the insert function, but I cannot figure it out.
You can simplify this by making the Hashtable an array of pointers to Node. A nullptr then means the slot is empty and you don't have empty and full nodes. Also Nodes only need a next pointer and usually new entries are added to the beginning of the buckets instead of the end (allows duplicate entries to "replace" older ones). Inserting at the beginning of a list becomes real easy with Node **.
#include <cstddef>
#include <iostream>
struct Table {
struct Node {
Node * next;
int data;
Node(Node **prev, int data_) : next{*prev}, data{data_} {
*prev = this;
}
};
std::size_t size;
Node **tbl;
Table(std::size_t size_) : size{size_}, tbl{new Node*[size]} { }
~Table() {
for (std::size_t i = 0; i < size; ++i) {
Node *p = tbl[i];
while(p) {
Node *t = p->next;
delete p;
p = t;
}
}
delete[] tbl;
}
void insert(int value) {
Node **slot = &tbl[value % size];
new Node(slot, value);
}
void display() const {
for(std::size_t i = 0; i < size; i++) {
std::cout << "Slot " << i << ":";
for (const Node *node = tbl[i]; node; node = node->next) {
std::cout << " " << node->data;
}
std::cout << std::endl;
}
}
};
int main(){
std::size_t size;
std::cout << "Enter size of the hash table: ";
std::cin >> size;
Table table{size};
int value;
std::cout << "Enter Value: ";
std::cin >> value;
//inserting single value
table.insert(value);
//Hash table output.
table.display();
return 0;
}
I have a program in which I'm supposed to build functions using linked lists to perform a variety of tasks. Currently, I am having an issue finding the min and max value of the linked list. For some reason when both come out to be the highest which digit which is 9, and when I try to find the average of the list, it still comes out as 9.
additionally, I think it's interfering with my pop function which is supposed to delete the last item, but when I try to work it by sections one part wont work until he previous section is running for whatever reason.
here is my header
#include <iostream>
using std::cout;
using std::endl;
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinkedList
{
private:
struct Node
{
int data;
Node *next;
};
int size;
Node *head, *tail;
public:
LinkedList();
~LinkedList();
// misc
void display();
// sorting and searching
// reverse --> sorting in descending
int linearSearch(int key);
void sort();
void reverse();
// various math
int min();
int max();
int mean();
// adding
void append(int num);
void insert(int num, int pos);
// removing
void pop();
void remove(int pos);
};
#endif // LINKEDLIST_H
the header's source file
#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--;
}
void LinkedList::insert(int num, int pos)
{
if(pos ==0)
{
Node *temp=new Node;
temp->data=num;
temp->next=head;
head=temp;
}
if(pos>1)
{
Node *pre=new Node;
Node *cur=new Node;
Node *temp=new Node;
cur=head;
for(int i=1;i<pos+1;i++)
{
pre=cur;
cur=cur->next;
}
temp->data=num;
pre->next=temp;
temp->next=cur;
}
size++;
}
int LinkedList::linearSearch(int key)
{
Node *temp = head;
for(int i = 0; i < size; i++)
{
if(temp->data == key)
{
return i;
}
temp = temp->next;
}
return -1;
}
int LinkedList::max()
{
int max = INT_MIN;
for(int i = 0; i < size; i++)
{
while (head != NULL)
{
if (head->data < max)
max = head->data;
head = head->next;
}
}
}
int LinkedList::min()
{
int min = INT_MAX;
for(int i = 0; i < size; i++)
{
while (head != NULL)
{
if (head->data < min)
min = head->data;
head = head->next;
}
}
}
void LinkedList::reverse()
{
Node* temp = head;
// Traverse the List
while (temp) {
Node* min = temp;
Node* r = temp->next;
// Traverse the unsorted sublist
while (r)
{
if (min->data < r->data)
min = r;
r = r->next;
}
// Swap Data
int x = temp->data;
temp->data = min->data;
min->data = x;
temp = temp->next;
}
}
void LinkedList::remove(int pos)
{
Node *temp = head;
if(pos ==0)
{
head = temp->next;
free(temp);
}
if(pos>1)
{
for(int i=0; temp!=NULL && i<pos-1;i++)
{
temp=temp->next;
}
temp->next = temp->next->next;
free(temp->next);
temp->next = temp->next;
}
size--;
}
int LinkedList::mean()
{
int sum = 0;
float avg = 0.0;
Node *temp = head;
while (head != NULL)
{
sum += temp->data;
temp = temp->next;
}
// calculate average
avg = (double)sum / size;
}
void LinkedList::sort()
{
Node* temp = head;
// Traverse the List
while (temp) {
Node* min = temp;
Node* r = temp->next;
// Traverse the unsorted sublist
while (r) {
if (min->data > r->data)
min = r;
r = r->next;
}
// Swap Data
int x = temp->data;
temp->data = min->data;
min->data = x;
temp = temp->next;
}
}
And the main
#include <iostream>
#include "linkedlist.h"
using namespace std;
int main()
{
LinkedList nums;
// adding through append
nums.append(8);
nums.append(6);
nums.append(7);
nums.append(8);
nums.append(0);
nums.append(9);
// displays list
cout << "List after append: " << endl;
nums.display();
cout << endl;
// adding through insert
nums.insert(1, 0);
nums.insert(5, 4);
nums.insert(3, 8);
// displays list
cout << "List after inserting: " << endl;
nums.display();
cout << endl;
// testing searching
cout << "Testing linear search:" << endl;
int pres = nums.linearSearch(7);
if(pres < 0)
{
cout << "7 is not present in the list." << endl;
}
else
{
cout << "7 can be found at location " << pres << endl;
}
pres = nums.linearSearch(5);
if(pres < 0)
{
cout << "5 is not present in the list." << endl;
}
else
{
cout << "5 can be found at location " << pres << endl;
}
cout << endl;
// does math
cout << "Minimum, maximum, and average before removing any items: " << endl;
cout << "Min: " << nums.min() << endl;
cout << "Max: " << nums.max() << endl;
cout << "Mean: " << nums.mean() << endl << endl;
// displays items reversed
cout << "Items reversed: " << endl;
nums.reverse();
nums.display();
cout << endl;
// removing through pop
nums.pop();
nums.pop();
// displays list
cout << "List after popping: " << endl;
nums.display();
cout << endl;
// removing through remove
nums.remove(0);
nums.remove(2);
nums.remove(4);
// displays list
cout << "List after removing: " << endl;
nums.display();
cout << endl;
// displays items sorted
cout << "Items sorted: " << endl;
nums.sort();
nums.display();
cout << endl;
// does math
cout << "Minimum, maximum, and average after removing items: " << endl;
cout << "Min: " << nums.min() << endl;
cout << "Max: " << nums.max() << endl;
cout << "Mean: " << nums.mean() << endl << endl;
// testing searching
cout << "Testing linear search:" << endl;
pres = nums.linearSearch(7);
if(pres < 0)
{
cout << "7 is not present in the list." << endl;
}
else
{
cout << "7 can be found at location " << pres << endl;
}
pres = nums.linearSearch(5);
if(pres < 0)
{
cout << "5 is not present in the list." << endl;
}
else
{
cout << "5 can be found at location " << pres << endl;
}
return 0;
}
the only parts I'm really struggling with is the max, min, and mean along with getting my pop function to actually initiate. I know that the pop function is written correctly but ever since I made the max and min it wont work now.
There are several bugs that I have found in the code, and I have several remarks about it:
You should use spaces, and more consistently. There are places without enough spacing, and places with too many blank lines!
If you have two functions such as insert and append or pop and remove, they should use each other, meaning, append is just insert(0) (notice how I changed it in the code).
You are using double loops where it doesn't make sense (it isn't an error, but it is a bug!).
In the function max, you were doing the wrong comparison, asking if max is bigger than the current value...
You never return a value from min and max, which should at least create a warning in the compilation process!
You were creating empty nodes, and then you just put different values in their pointers, meaning that this new memory was still allocated (since there was no delete), but there was no way to access these anymore (this is a memory leak).
The biggest bug of all - When you loop in the min and max functions, you change the head of the list, which is a major bug (and that is why you got bugs after using this function). The solution is a simple but important lesson in C++ - Const Correctness.
What is const correctness, and why is it important?
When you have a function, that does not change the state of your object, it should be declared const. This is our way to tell the compiler (and other programmers) that it mustn't change the state of our object. For example, min, max and average are classic const functions - they simply make a calculation that does not change the list, and return. If you had written const in the declaration of those, the compilation would have failed, since you actually changed the list (changing the head), although you shouldn't!
Moreover, when receiving objects into a function, whenever possible, you should make the const T& where T is a type. They will enforce that you are using only const functions of this type.
Also, I suggest compiling (at least on g++) with the flags -Wpedantic -Werror'. The first adds some warnings about ISO C++ standards and the second makes all warnings into errors (and thus, yourmin,maxandmean` should not compile, since they don't return a value).
Here is the code:
class LinkedList
{
private:
struct Node
{
int data;
Node *next;
Node(int data_, Node* next_ = nullptr) :
data(data_),
next(next_)
{
}
};
int size;
Node *head, *tail;
public:
LinkedList();
~LinkedList();
void clear();
// various math
int min() const;
int max() const;
int average() const;
// adding
void append(int data);
void insert(int data, int pos);
// removing
void pop();
void remove(int pos);
};
LinkedList::LinkedList()
{
head = nullptr;
tail = nullptr;
size = 0;
}
LinkedList::~LinkedList()
{
clear();
}
void LinkedList::clear()
{
if (head != nullptr)
{
Node *temp;
while(head != nullptr)
{
temp = head->next;
delete head;
head = temp;
}
}
head = nullptr;
tail = nullptr;
size = 0;
}
void LinkedList::display()
{
Node *temp = head;
for(int i = 0; i < size; i++)
{
std::cout << temp->data << "\t";
temp = temp->next;
}
std::cout << std::endl;
}
void LinkedList::insert(int data, int pos)
{
if (pos == 0)
{
Node* prev_head = head;
head = new Node(data, prev_head);
if (size == 0)
{
tail = head;
}
}
else
{
Node *pre=nullptr;
Node *cur = head;
for(int i = 0 ; i < pos + 1; ++i)
{
pre = cur;
cur = cur->next;
}
Node *temp = new Node(data, cur);
pre->next = temp;
}
++size;
}
void LinkedList::append(int data)
{
insert(data, 0);
}
void LinkedList::pop()
{
if (size == 1)
{
Node *temp = tail;
head = nullptr;
tail = nullptr;
delete temp;
}
else
{
Node *temp = head;
while(temp->next != tail)
{
temp = temp->next;
}
Node* node_to_pop = tail;
tail = temp;
tail->next = nullptr;
delete node_to_pop;
}
--size;
}
int LinkedList::max() const
{
int max = INT_MIN;
for (Node* temp = head; temp != nullptr; temp = temp->next)
{
if (temp->data > max)
{
max = temp->data;
}
}
return max;
}
int LinkedList::min() const
{
int min = INT_MAX;
for(Node* temp = head; temp != nullptr; temp = temp->next)
{
if (head->data < min)
{
min = temp->data;
}
}
return min;
}
int LinkedList::average() const
{
int sum = 0;
for(Node* temp = head; temp != nullptr; temp = temp->next)
{
sum += temp->data;
temp = temp->next;
}
return (double)sum / size;
}
I am writing chained hash table code.
I do not understand why my linked list traversal does not stop at NULL when I set entry->next->next = NULL after I insert.
I have omitted code which is not useful for my question:
What is causing the linked list traversal in `printTable' to loop forever?
ChainHash.h:
class Entry {
private:
string key;
int value;
Entry *next;
friend class HashTable_CH;
public:
Entry(string k, int v) {
key = k;
value = v;
next = NULL;
}
};
class HashTable_CH {
private:
Entry **slots;
const int DEFAULT_CAP = 11;
const float load_factor = 0.5;
int capacity;
int size;
//int isPrime(int n) {
//int calculateGrowSize() {
int hash(string k) {
int c = 0;
for (int i = 0; i < k.length(); i++)
c += int(k[i]);
return c % capacity;
}
//int probe(int hash, int index) {
public:
HashTable_CH() {
slots = new Entry*[DEFAULT_CAP];
capacity = DEFAULT_CAP;
size = 0;
for (int i = 0; i < DEFAULT_CAP; i++)
slots[i] = NULL;
}
void Insert(string key, int value) {
if (float(size) / float(capacity) >= load_factor)
//grow();
return;
int h = hash(key);
if (slots[h] == NULL) {
slots[h] = new Entry(key, value);
size++;
return;
} else {
Entry *entry = slots[h];
while (entry->next != NULL)
entry = entry->next;
entry->next = new Entry(key, value);
entry->next->next = NULL;
}
}
//bool Search(string, int &value) {
//void Remove(string key) {
void printTable() {
for (int i = 0; i < capacity; i++) {
cout << "Slot " << i << ": ";
if (slots[i] == NULL)
cout << "*****";
else {
Entry **temp = slots;
while (temp != NULL) {
cout << "Key: " << slots[i]->key << ", " << slots[i]->value;
}
}
} cout << "\n";
} cout << "\n";
}
};
testChainedHash.cpp:
#include"ChainHash.h"
int main() {
HashTable_CH t1;
t1.Insert("froyo", 500);
t1.Insert("froyo", 600);
t1.Insert("froyo", 700);
t1.printTable();
}
Here:
while (temp != NULL) {
cout << "Key: " << slots[i]->key << ", " << slots[i]->value;
}
Do you see the problem?
I am working on writing a list of children binary tree implementation. In my code I have an array of lists. Each list contains a node followed by its children on the tree. I finished writing the code and everything compiled, but I keep getting a segmentation fault error and I cannot figure out why. I have been attempting to debug and figure out where my code messes up. I know that there is an issue with the FIRST function. It causes a segmentation fault. Also, when I try to print just one of the lists of the array, it prints everything. I have been stuck on this for a very long time now and would like some help. Can anyone offer suggestions as to why the FIRST and PRINT functions are not working? Maybe there is a large error that I just cannot see.
My code is as follows:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <array>
#include <string.h>
using namespace std;
struct node
{
char element;
struct node *next;
}*start;
class list
{
public:
void ADD(char n);
node* CREATE(char n);
void BEGIN(char n);
char FIRST();
char END();
char NEXT(char n);
char PREVIOUS(char n);
int LOCATE(char n);
void EMPTY();
void PRINT();
list()
{
start = NULL;
}
};
char PARENT(const char n, list tree[], int length)
{
int i=0;
list l;
for (i; i<length; i++)
{
l = tree[i];
if (n != l.FIRST())
{
if (l.LOCATE(n)>0)
return l.FIRST();
}
}
}
char LEFTMOST_CHILD(char n, list tree[], int length)
{
int i;
list l;
for (i=0; i<length; i++)
{
l = tree[i];
if (l.FIRST() == n)
return l.NEXT(n);
}
}
char RIGHT_SIBLING(char n, list tree[], int length)
{
int i;
list l;
for (i=0; i<length; i++)
{
l = tree[i];
if(n != l.FIRST())
{
if (l.LOCATE(n) > 0)
{
return l.NEXT(n);
}
}
}
}
char ROOT(list tree[]) //assumes array is in order, root is first item
{
list l;
l = tree[0];
cout << "Assigned tree to l" << endl;
return l.FIRST();
}
void MAKENULL(list tree[], int length)
{
int i;
list l;
for (i=0; i<length; i++)
{
l = tree[i];
l.EMPTY();
}
}
void list::PRINT()
{
struct node *temp;
if (start == NULL)
{
cout << "The list is empty" << endl;
return;
}
temp = start;
cout << "The list is: " << endl;
while (temp != NULL)
{
cout << temp->element << "->" ;
temp = temp->next;
}
cout << "NULL" << endl << endl;
}
void list::EMPTY()
{
struct node *s, *n;
s = start;
while (s != NULL)
{
n = s->next;
free(s);
s = n;
}
start = NULL;
}
int list::LOCATE(char n)
{
int pos = 0;
bool flag = false;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->element == n)
{
flag == true;
return pos;
}
s = s->next;
}
if (!flag)
return -1;
}
void list::ADD(char n)
{
struct node *temp, *s;
temp = CREATE(n);
s = start;
while (s->next != NULL)
s = s->next;
temp->next = NULL;
s->next = temp;
}
node *list::CREATE(char n)
{
struct node *temp;
temp = new(struct node);
temp->element = n;
temp->next = NULL;
return temp;
}
void list::BEGIN(char n)
{
struct node *temp, *p;
temp = CREATE(n);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
}
char list::FIRST()
{
char n;
struct node *s;
s = start;
cout << "s = start" << endl;
n = s->element;
cout << "n" << endl;
return n;
}
char list::END()
{
struct node *s;
s = start;
int n;
while (s != NULL)
{
n = s->element;
s = s->next;
}
return n;
}
char list::NEXT(char n)
{
char next;
struct node *s;
s = start;
while (s != NULL)
{
if (s->element == n)
break;
s = s->next;
}
s = s->next;
next = s->element;
return next;
}
char list::PREVIOUS(char n)
{
char previous;
struct node *s;
s = start;
while (s != NULL)
{
previous = s->element;
s = s->next;
if (s->element == n)
break;
}
return previous;
}
main()
{
list a,b,c,d,e,f,g,h,i,j,k,l,m,n;
a.BEGIN('A');
b.BEGIN('B');
c.BEGIN('C');
d.BEGIN('D');
e.BEGIN('E');
f.BEGIN('F');
g.BEGIN('G');
h.BEGIN('H');
i.BEGIN('I');
j.BEGIN('J');
k.BEGIN('K');
l.BEGIN('L');
m.BEGIN('M');
n.BEGIN('N');
a.ADD('B');
a.ADD('C');
b.ADD('D');
b.ADD('E');
e.ADD('I');
i.ADD('M');
i.ADD('N');
c.ADD('F');
c.ADD('G');
c.ADD('H');
g.ADD('J');
g.ADD('K');
h.ADD('L');
a.PRINT();
list tree[] = {a,b,c,d,e,f,g,h,i,j,k,l,m,n};
int length = sizeof(tree)/sizeof(char);
char root = ROOT(tree);
cout << "Found root" << endl;
char parent = PARENT('G', tree, length);
cout << "Found Parent" << endl;
char leftChild = LEFTMOST_CHILD('C', tree, length);
cout << "found left child" << endl;
char rightSibling = RIGHT_SIBLING('D', tree, length);
cout << "found right sibling" << endl;
cout << "The root of the tree is: ";
cout << root << endl;
cout << "The parent of G is: ";
cout << parent << endl;
cout << "The leftmost child of C is" ;
cout << leftChild << endl;
cout << "The right sibling of D is: " ;
cout << rightSibling << endl;
}
Any help will be very appreciated. Thanks you!
The fundamental problem is that you have written a lot of code before testing any of it. When you write code, start with something small and simple that works perfectly, add complexity a little at a time, test at every step, and never add to code that doesn't work.
The specific problem (or at least one fatal problem) is here:
struct node
{
char element;
struct node *next;
}*start;
class list
{
public:
//...
list()
{
start = NULL;
}
};
The variable start is a global variable. The class list has no member variables, but uses the global variable. It sets start to NULL every time a list is constructed, and every list messes with the same pointer. The function FIRST dereferences a pointer without checking whether the pointer is NULL, and when it is, you get Undefined Behavior.
It's not entirely clear what you intended, but you seem to misunderstand how variables work in C++.
I am using Visual Studio 2013, running on windows 7 64 bit.
I am trying to display a language different than English. My code is:
#include <iostream>
#include <string>
using namespace std;
typedef char byte;
byte text[] = "текст";
int text_len;
struct Huf {
byte id;
int wh;
Huf *left, *right;
};
struct List {
List *next;
Huf *tree;
};
List *head;
char code[256];
void createList();
void writeList();
void delList(List *);
void addList(Huf *);
Huf *findDels();
void createTree();
void rlrootTree(Huf *, unsigned);
int main()
{
text_len = strlen(text);
createList();
writeList();
createTree();
cout << "writeCodes\n";
rlrootTree(head->tree, 0);
cout << endl;
system("pause");
return 0;
}
void createList()
{
int i;
int ch[256] = { 0 };
for (i = 0; i<text_len; i++) ch[text[i]]++;
List *l;
Huf *h;
head = 0;
for (i = 0; i<255; i++) if (ch[i]>0)
{
h = new Huf;
h->id = i; h->wh = ch[i];
h->left = 0; h->right = 0;
l = new List;
l->tree = h;
l->next = head; head = l;
}
}
void writeList()
{
cout << "writeList\n";
List *l = head;
while (l)
{
cout << (l->tree)->id << " ";
l = l->next;
}
cout << endl;
l = head;
while (l)
{
cout << (l->tree)->wh << " ";
l = l->next;
}
cout << endl;
}
void delList(List *l)
{
List *lp, *lc;
if (l == head) { head = l->next; delete l; }
else
{
lp = head; lc = lp->next;
while (lc != l) { lp = lc; lc = lc->next; }
lp->next = lc->next; delete lc;
}
}
void addList(Huf *h)
{
List *l = new List;
l->tree = h;
l->next = head;
head = l;
}
Huf *findDels()
{
List *l = head, *sm = head;
Huf *h;
while (l)
{
if ((l->tree)->wh < (sm->tree)->wh) sm = l;
l = l->next;
}
h = sm->tree;
delList(sm);
return h;
}
void createTree()
{
Huf *h, *h1, *h2;
while (head->next)
{
h1 = findDels();
h2 = findDels();
h = new Huf;
h->id = ' '; h->wh = h1->wh + h2->wh;
h->left = h1; h->right = h2;
addList(h);
}
}
void rlrootTree(Huf *h, unsigned index)
{
if (h)
{
code[index] = '0';
rlrootTree(h->right, index + 1);
if (h->left == 0)
{
code[index] = '\0';
cout << h->id << "->" << code << " ";
}
code[index] = '1';
rlrootTree(h->left, index + 1);
}
}
I have tried adding <locale> and <windows.h> includes with AnsiToOem() but it doesnt seem to compile - I get character errors.
You are iterating through the text byte by byte. But each letter (grapheme) consists of two code units, that is two bytes.
To make this simple I would store the string as an array of char32_t, because then the whole codepoint (one grapheme) would fit in one element of the array.
If you want to be able to handle absolutely every international "character" you would also have to handle grapheme clusters then you would have have a look at the ICU library or similar.
A dangerously simplified suggestion:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
typedef char32_t byte;
byte text[] = U"текст";
int text_len;
struct Huf {
byte id;
int wh;
Huf *left, *right;
};
struct List {
List *next;
Huf *tree;
};
List *head;
char code[16000];
void createList();
void writeList();
void delList(List *);
void addList(Huf *);
Huf *findDels();
void createTree();
void rlrootTree(Huf *, unsigned);
unsigned strlen(char32_t* st) {
unsigned len = 0;
while (*(st+len) != 0) ++len;
return len;
}
int main()
{
text_len = strlen(text);
std::cout << "len = " << text_len << std::endl;
createList();
writeList();
createTree();
cout << "writeCodes\n";
rlrootTree(head->tree, 0);
cout << endl;
system("pause");
return 0;
}
void createList()
{
int i;
int ch[16000] = { 0 }; //you really need more here
for (i = 0; i<text_len; i++) ch[text[i]]++;
List *l;
Huf *h;
head = 0;
for (i = 0; i<16000; i++) if (ch[i]>0)
{
h = new Huf;
h->id = i; h->wh = ch[i];
h->left = 0; h->right = 0;
l = new List;
l->tree = h;
l->next = head; head = l;
}
}
void writeList()
{
cout << "writeList\n";
List *l = head;
while (l)
{
cout << (l->tree)->id << " ";
l = l->next;
}
cout << endl;
l = head;
while (l)
{
cout << (l->tree)->wh << " ";
l = l->next;
}
cout << endl;
}
void delList(List *l)
{
List *lp, *lc;
if (l == head) { head = l->next; delete l; }
else
{
lp = head; lc = lp->next;
while (lc != l) { lp = lc; lc = lc->next; }
lp->next = lc->next; delete lc;
}
}
void addList(Huf *h)
{
List *l = new List;
l->tree = h;
l->next = head;
head = l;
}
Huf *findDels()
{
List *l = head, *sm = head;
Huf *h;
while (l)
{
if ((l->tree)->wh < (sm->tree)->wh) sm = l;
l = l->next;
}
h = sm->tree;
delList(sm);
return h;
}
void createTree()
{
Huf *h, *h1, *h2;
while (head->next)
{
h1 = findDels();
h2 = findDels();
h = new Huf;
h->id = ' '; h->wh = h1->wh + h2->wh;
h->left = h1; h->right = h2;
addList(h);
}
}
void rlrootTree(Huf *h, unsigned index)
{
if (h)
{
code[index] = '0';
rlrootTree(h->right, index + 1);
if (h->left == 0)
{
code[index] = '\0';
cout << h->id << "->" << code << " ";
}
code[index] = '1';
rlrootTree(h->left, index + 1);
}
}