C++ How To Make a Dictionary With Binary Search Tree - c++

I want to make a dictionary but I can not output 2 tree in my code
and I don't know what to do next:
WORD *t1 = NULL;
WORD *t2 = NULL;
WORD *t = NULL;
void InsertWordEN(WORD *t1, TD x)
{
if(t1 == NULL)
{
WORD *temp;
temp = new WORD;
strcpy(temp->data.EN, x.EN);
temp->left = NULL;
temp->right = NULL;
t1 = temp;
}
else
{
if (strcmp(t1->data.EN, x.EN) == 1)
{
InsertWordEN(t1->left,x);
}
else if(strcmp(t1->data.EN, x.EN) == 0)
{
InsertWordEN(t1->right,x);
}
}
}
void InsertWordVN(WORD *t2, TD x)
{
if(t2 == NULL)
{
WORD *temp;
temp = new WORD;
strcpy(temp->data.VN, x.VN);
temp->left = NULL;
temp->right = NULL;
t2 = temp;
}
else
{
if (strcmp(t2->data.VN, x.VN) == 1)
{
InsertWordVN(t2->left,x);
}
else if(strcmp(t2->data.VN, x.VN) == 0)
{
InsertWordVN(t2->right,x);
}
}
}
void InsertWord(TD &x)
{
cout<<"\EN: "; cin>>x.EN;
InsertWordEN(t1,x);
cout<<"\nVN: "; cin>>x.VN;
InsertWordEN(t2,x);
}
void OutputWord_NLR(WORD *t)
{
if(t1 != NULL)
{
cout<<t1->data.EN<<" ";
OutputWord_NLR(t1->left);
OutputWord_NLR(t1->right);
}
else if(t2 != NULL)
{
cout<<t2->data.VN<<" ";
OutputWord_NLR(t2->left);
OutputWord_NLR(t2->right);
}
}
int main()
{
int select; TD x;
InsertWord(x);
cout<<"\nOutput Tree EN and VN";
OutputWord_NLR(t);
getch();
return 0;
}
I think OutputWord_NLR function is wrong ?
BTS. It's too hard for me . I'm trying to understand it :)
Sorry ! It's seems too long . So I can't send at all my code

Related

Printing output with format (page x)-> in cpp

Please provide the implementation of functions append, printList, and delete_evens as described in the comments. You will be dealing with a linked list of pages in which every node (page), is linked to its next and previous node (page) using next and prev pointers respectively. Please note the previous node of the first node (head) is NULL. In a similar way, the next of the last node will also be NULL.
The expected output is as follows:
Created PageList:
(page1)->(page2)->(page3)->(page4)->(page5)->(page6)->(page7)->(page8)->(page9)->(page10)->(page11)->(page12)->(page13)->(page14)->(page15)->(page16)->(page17)->(page18)->(page19)->(page20)->(page21)->(page22)->(page23)->(page24)->(page25)->(page26)->(page27)->(page28)->(page29)->(page30)->(page31)->(page32)->(page33)->(page34)->(page35)->(page36)->(page37)->(page38)->(page39)->(page40)->(page41)->(page42)->(page43)->(page44)->(page45)->(page46)->(page47)->(page48)->(page49)->(page50)->
Updated PageList:
(page1)->(page3)->(page5)->(page7)->(page9)->(page11)->(page13)->(page15)->(page17)->(page19)->(page21)->(page23)->(page25)->(page27)->(page29)->(page31)->(page33)->(page35)->(page37)->(page39)->(page41)->(page43)->(page45)->(page47)->(page49)->
The output I am getting is:
Created PageList:
(page)->1 (page)->2 (page)->3 (page)->4 (page)->5 (page)->6 (page)->7 (page)->8 (page)->9 (page)->10 (page)->11 (page)->12 (page)->13 (page)->14 (page)->15 (page)->16 (page)->17 (page)->18 (page)->19 (page)->20 (page)->21 (page)->22 (page)->23 (page)->24 (page)->25 (page)->26 (page)->27 (page)->28 (page)->29 (page)->30 (page)->31 (page)->32 (page)->33 (page)->34 (page)->35 (page)->36 (page)->37 (page)->38 (page)->39 (page)->40 (page)->41 (page)->42 (page)->43 (page)->44 (page)->45 (page)->46 (page)->47 (page)->48 (page)->49 (page)->50
Updated PageList:
(page)->1 (page)->3 (page)->5 (page)->7 (page)->9 (page)->11 (page)->13 (page)->15 (page)->17 (page)->19 (page)->21 (page)->23 (page)->25 (page)->27 (page)->29 (page)->31 (page)->33 (page)->35 (page)->37 (page)->39 (page)->41 (page)->43 (page)->45 (page)->47 (page)->49
My code is as follows:
#include <iostream>
#include <string>
using namespace std;
class Page {
public:
int page_number = 0;
string page_content = "";
Page *next = NULL;
Page *prev = NULL; // previous
};
class PageList {
public:
Page *head = NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content) {
Page *first;
first = new Page();
first->page_content = page_content;
first->next = NULL;
first->prev = NULL;
first->page_number = page_number;
if (head == NULL) {
head = first;
} else {
Page *second = head;
while (second->next != NULL) {
second = second->next;
}
second->next = first;
}
}
// print all the elements of the list (pages) with the given format
void print list(Page *node, bool forward) {
while (node != NULL) {
cout << node->page_content << " ";
node = node->next;
}
cout << endl;
}
void delete_evens() { // delete the pages with even page_number
Page *first = head;
Page *q = NULL;
while (first != NULL) {
if (first->page_number % 2 == 0) {
if (q == NULL) {
head = first->next;
first = first->next;
} else {
q->next = first->next;
first->next = NULL;
first = q->next;
}
} else {
if (q == NULL) {
q = first;
first = first->next;
} else {
q = q->next;
first = first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i = 1; i <= pages; i++) {
append(i, "(page" + to_string(i));
}
cout << "Created PageList:" << endl;
printList(head, true);
delete_evens();
cout << "Updated PageList:" << endl;
printList(head, true);
}
};
int main() {
PageList list(50);
return 0;
}
I believe that the error is somewhere in the line append(i, "(page" + to_string(i));
Can someone please help?
#include <iostream>
#include <string>
using namespace std;
// -------------------------------------------------------------------
class Page {
public:
int page_number = 0;
string page_content = "";
Page* next = NULL;
Page* prev = NULL;// previous
};
class PageList {
public:
Page* head=NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content){
Page* first;
first=new Page();
first->page_content = page_content;
first->next=NULL;
first->prev=NULL;
first->page_number=page_number;
if(head==NULL) {
head=first;
}
else{
Page* second=head;
while(second->next != NULL) {
second=second->next;
}
second->next=first;
}
}
// print all the elements of the list (pages) with the given format
void printList(Page* node, bool forward) {
while(node != NULL) {
cout<<node->page_content<<""<<")->";;
node=node->next;
}
cout<<endl;
}
void delete_evens() // delete the pages with even page_number
{
Page* first = head;
Page* q=NULL;
while(first != NULL)
{
if(first->page_number % 2 == 0)
{
if(q==NULL)
{
head=first->next;
first=first->next;
}
else
{
q->next=first->next;
first->next=NULL;
first=q->next;
}
}
else
{
if(q==NULL)
{
q=first;
first=first->next;
}
else
{
q=q->next;
first=first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i=1;i<=pages;i++){
append(i, "(page" + to_string(i));
}
cout<< "Created PageList:" << endl;
printList(head,true);
delete_evens();
cout<< "Updated PageList:" << endl;
printList(head,true);
}
};
// -------------------------------------------------------------------
int main()
{
PageList list(50);
return 0;
}

Implementation of Queue in C++

When I study the DataStructrue in my school, I implemented the Queue.
School's DataStructure class process is below.
student implemnted the DS
student submit in Domjudge
Domjudge score the code based by test cases.
My freind implemented the Queue like below.
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {}
Node(int e) {
this->data = e;
this->next = NULL;
}
~Node(){}
};
class SLinkedList {
public:
Node* head;
Node* tail;
SLinkedList() {
head = NULL;
tail = NULL;
}
void addFront(int X) {
Node* v = new Node(X); // new Node
if (head == NULL) {
// list is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int removeFront() {
if (head == NULL) {
return -1;
}else{
Node* tmp = head;
int result = head->data;
head = head->next;
delete tmp;
return result;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
void addBack(int X) {
Node* v = new Node(X);
if (head == NULL) {
head = tail = v;
}else {
tail->next = v;
tail = v;
}
}
~SLinkedList() {}
};
class LinkedQ {
public:
int n = 0;
int capacity;
Node* f;
Node* r;
SLinkedList Q;
LinkedQ(int size) {
capacity = size;
f = NULL;
r = NULL;
}
bool isEmpty() {
return n == 0;
}
int size() {
return n;
}
int front() {
return Q.front();
}
int rear() {
return Q.rear();
}
void enqueue(int data) {
if (n == capacity) {
cout << "Full\n";
}else {
Q.addBack(data);
n++;
}
}
};
int main() {
int s, n;
string cmd;
cin >> s >> n;
listQueue q(s);
for (int i = 0; i < n; i++) {
cin >> cmd;
if (cmd == "enqueue") {
int x;
cin >> x;
q.enqueue(x);
}else if (cmd == "size") {
cout << q.size() << "\n";
}else if (cmd == "isEmpty") {
cout << q.isEmpty() << "\n";
}else if (cmd == "front") {
q.front();
}else if (cmd == "rear") {
q.rear();
}
}
}
And I implmented like this (Node class and main are same, So I pass the code)
#include <iostream>
#include <string>
using namespace std;
class Node{...};
class listQueue {
public:
Node* head;
Node* tail;
int capacity;
int n = 0;
listQueue() {
head = NULL;
tail = NULL;
}
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) {
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}
int front() {
if (head == NULL) {
return -1;
}else {
return head->data;
}
}
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
int empty() {
if (head == NULL) {
return 1;
}else {
return 0;
}
}
~listQueue() {}
};
test cases are just enqueue
but my friend is correct, and my code has occured memory over error.
So I check the usage of memory in Domjudge, My friend code and My code has very big gap in memory usage.
Why these two codes have memory usage gap big?
P.S I can't speak English well. If there is something you don't understand, please tell me.
First, rear is incorrect. It checks head and return tail. It happens to correct when you first set head=tail=v but it might get wrong later.
int rear() {
if (head == NULL) {
return -1;
}else {
return tail->data;
}
}
Check the if statement below:
v is leaked if queue is full in enqueue in your implementation.
Don't use NULL in C++. You may refer to NULL vs nullptr (Why was it replaced?).
void enqueue(int X) {
Node* v = new Node(X); // new Node
if (n==capacity) { // You're leaking v;
cout << "Full\n";
return;
}
if (head == NULL) {
// Queue is empty
head = tail = v;
}else {
v->next = head;
head = v;
}
}

Doubly Linked List fails to add or delete valid entries

I've run it many times. I tried fixing my deleteNode() and addNode(), but it did not work. The output showed me that it failed to add some valid entries in my list, which resulted in failing to delete these valid entries. Someone please help me find the errors... I think either my isEmpty() is wrong or the addNode got messed up.
// Add nodes and makes it work in any cases: backward/forward
bool LinkedList::addNode(int id, string str) {
bool result = false;
if (id >= 0 && !(idExists(id))) {
Node *current = head;
Node *temp = new Node;
temp->data.data = str;
temp->data.id = id;
temp->forward = NULL;
temp->back = NULL;
// Kinds of adding cases
if(head == NULL) { // Check if list is empty
addHead(temp, current);
result = true;
} else {
while(temp->data.id > current->data.id && current->forward != NULL) {
current = current->forward;
}
// Backward
if(current->back == NULL) {
if(temp->data.id > current->data.id) {
if(current->forward == NULL) {
addTail(temp, current);
} else {
addMiddle(temp, current);
}
} else {
addHead(temp, current);
}
result = true;
// Forward
}else if(current->forward == NULL) {
if (temp->data.id > current->data.id) {
addTail(temp, current);
} else {
addMiddle(temp, current);
}
result = true;
}else {
if(temp->data.id > current->data.id) {
addMiddle(temp, current);
result = true;
}
}
}
}
return result;
}
void LinkedList::addHead(Node *temp, Node *current) {
if (head != NULL){
temp->forward = current;
current->back = temp;
head = temp;
} else {
head = temp;
}
}
void LinkedList::addMiddle(Node *temp, Node *current) {
temp->forward = current;
temp->back = current->back;
current->back->forward = temp;
current->back = temp;
}
void LinkedList::addTail(Node *temp, Node *current) {
current->forward = temp;
temp->back = current;
}
// Delete list
bool LinkedList::deleteNode(int id){
bool result = false;
if (idExists(id)) {
Node *current = head;
while (current->forward != NULL && current->data.id != id) {
current = current->forward;
}
if (current->data.id == id && current->forward == NULL) {
if (current->back == NULL) { // Delete head
delete current;
head = NULL;
} else { // delete tail
deleteTail(current);
}
result = true;
} else if (current->data.id == id) {
if (current->back == NULL)
deleteHead(current);
else // delete middle
deleteMiddle(current);
result = true;
}
}
return result;
}
// Helper delete functions
void LinkedList::deleteHead(Node *current) {
head = current->forward;
head->back = NULL;
delete current;
}
void LinkedList::deleteMiddle(Node *current) {
current->back->forward = current->forward;
current->forward->back = current->back;
delete current;
}
void LinkedList::deleteTail(Node *current) {
current->back->forward = NULL;
delete current;
}
bool LinkedList::getNode(int id, Data *data) {
bool didGetNode = false;
if (idExists(id)) {
Node *current = head;
while (current->forward != NULL && current->data.id != id) {
current = current->forward;
}
data->id = current->data.id;
data->data = current->data.data;
didGetNode = true;
}
return didGetNode;
}
// Check whether or not the id exists
bool LinkedList::idExists(int id){
bool exists = false;
if (head != NULL){
Node *current = head;
while (current->forward != NULL && current->data.id != id) {
current = current->forward;
}
if (current->data.id == id) {
exists = true;
}
}
return exists;
}
You probably want to be passing a pointer to a pointer (**) or a pointer to a reference (*&) in functions where you are wanting to make a change to what the address of the node is containing. I hope that this helps you visualize it.
For example:
struct Node { };
void setNull1(Node* temp)
{
temp = nullptr;
}
void setNull2(Node** temp)
{
(*temp) = nullptr;
}
void setNull3(Node*& temp)
{
temp = nullptr;
}
int main()
{
Node* tmp = new Node;
setNull1(tmp);
if (tmp == nullptr)
{
cout << "NULLPTR";
} // tmp is not nullptr
Node* tmp1 = new Node;
setNull2(&tmp1);
if (tmp1 == nullptr)
{
cout << "NULLPTR";
} // tmp1 is nullptr
Node* tmp2 = new Node;
setNull3(tmp2);
if (tmp2 == nullptr)
{
cout << "NULLPTR";
} // tmp2 is nullptr
}
You should also consider writing nullptr instead of NULL.

Adjacency list to create graph and Breadth First Search (BFS) and Fepth First Search (DFS)

Here is my code which implements graph using adjacency list and do a Breadth First Search (BFS) and Depth First Search (DFS).
While creating graph and adding edges I am facing problem of a fault in creating graph. I am not sure of the pointer that I have used.
Can you suggest where am I wrong?
#include "Graph.h"
#include <iostream>
using namespace std;
int Graph::pop()
{
if (top = -1) {
cout << "empty";
return 0;
} else
return stack[top--];
}
void Graph::push(int value)
{
if (top >= 50) {
cout << "full";
} else
stack[++top] = value;
}
void Graph::add(int val)
{
if (rear != 49)
qu[++rear] = val;
else
cout << "full";
}
int Graph::del()
{
if (rear == front) {
cout << "empty";
return 0;
} else
front += 1;
return qu[front];
}
int Graph::gethead()
{
return rear;
}
int Graph::gettail()
{
return front;
}
node *Graph::createnode(int t)
{
node *temp;
temp = new node;
temp->val = t;
temp->next = NULL;
return temp;
}
Graph::Graph()
{
rear = -1;
front = -1;
top = -1;
}
Graph::Graph(int t)
{
struct arr r[t];
a = r;
for (int i = 0; i < t; i++) {
a[i].key = i;
a[i].begin = NULL;
a[i].end = NULL;
}
int q[t];
p = q;
for (int k = 0; k < t; k++) {
p[k] = 0;
}
}
void Graph::visited(int v1)
{
p[v1] = 1;
}
bool Graph::isvisited(int v1)
{
if (p[v1] == 1)
return true;
else
false;
}
void Graph::addEdge(int v1, int v2)
{
if (a[v1].begin == NULL) {
node *temp = createnode(v2);
a[v1].begin = temp;
a[v1].end = temp;
} else {
node *temp = createnode(v2);
node *temp1 = a[v1].end;
temp1->next = temp;
a[v1].end = temp;
}
if (a[v2].begin == NULL) {
node *temp = createnode(v1);
a[v2].begin = temp;
a[v2].end = temp;
} else {
node *temp = createnode(v1);
//node *temp2=a[v2].end;
//temp2->next=temp;
a[v2].end->next = temp;
//a[v2].end->next=temp;
a[v2].end = temp;
}
}
void Graph::deleteEdge(int v1, int v2)
{
node *temp;
temp = a[v1].begin;
if (a[v1].begin->val == v2) {
a[v1].begin = a[v1].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v2) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
node *temp1;
temp1 = a[v2].begin;
if (a[v2].begin->val == v1) {
a[v2].begin = a[v2].begin->next;
delete(temp);
temp = NULL;
} else {
node *t = temp->next;
while (t != NULL) {
if (t->val == v1) {
temp->next = t->next;
delete(t);
} else {
temp = t;
t = t->next;
}
}
}
}
void Graph::BFS(int source)
{
add(source);
visited(source);
node *temp = a[source].begin;
while (temp != a[source].end) {
add(temp->val);
}
int r = del();
cout << r << endl;
while (gethead() != gettail()) {
int v1 = del();
visited(v1);
node *temp1;
temp1 = a[v1].begin;
while (temp1 != NULL) {
if (p[temp1->val] != 1) {
add(temp1->val);
temp1 = temp1->next;
} else
temp1 = temp1->next;
}
if (temp1 == NULL)
cout << v1 << endl;
}
}
void Graph::DFS(int source)
{
int c = source;
cout << c;
visited(c);
node *temp2 = a[source].begin;
while (a[source].end != NULL) {
push(temp2->val);
temp2 = temp2->next;
}
c = pop();
while (top != -1) {
node *temp = a[c].begin;
if (p[c] != 1) {
cout << c;
while (temp != NULL) {
push(temp->val);
temp = temp->next;
visited(c);
c = pop();
}
}
if (p[c] = 1) {
c = pop();
}
}
}
The first obvious mistake is that in line if (top = -1), the = should be replaced with ==.

Delete return memory problems

I am writing a simple program for working with structure in C++. But there is a problem with memory. When my program calling a delete_element function it return memory's problem, but delete_all_list function working well. What I did wrong?
#include "iostream"
#include "string.h"
#include "limits" //ignore max
#include "stdlib.h" //atof
using namespace std;
struct Struct {
char text[10];
int age;
Struct *prev;
Struct *next;
};
int input(string msg) {
char str[2];
int check = 0, len = 0, var = 0, i = 0;
while (1){
cin.tellg();
cout<<msg;
cin.getline(str, 2);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
len = strlen(str);
check = 0;
for (i=0;i<len;i++) {
if(isdigit(str[i])) {
check++;
}
}
if (check==len && !(check==1 && str[0]=='-') && check != 0 && atoi(str) != 0){
var = atoi(str);
return var;
}
else {
cout<<"Error!"<<endl;
}
}
}
Struct* add_struct_to_list(Struct* prev){
Struct *NewStruct = 0;
char str[10];
int age;
cout<<"Name: ";
cin.getline(str, 10);
if (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
age = input("Age: ");
NewStruct = new Struct;
strcpy(NewStruct->text, str);
NewStruct->age = age;
NewStruct->prev= prev;
NewStruct->next= 0;
return NewStruct;
}
Struct* add_empty_struct_to_list(Struct* list_begin, int index){
int count = 1;
Struct* node = list_begin;
while (node->next) {
node = node->next;
count++;
}
while (count != index) {
Struct* NewStruct = new Struct;
strcpy(NewStruct->text, " ");
NewStruct->age = 0;
NewStruct->prev = node;
node->next = NewStruct;
NewStruct->next = NULL;
node = NewStruct;
count++;
}
return node;
}
void insert_struct_to_list(Struct* prev, Struct* next){
Struct *NewStruct = 0;
char str[10];
int age;
cout<<"Name: ";
cin.getline(str, 10);
if (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
age = input("Age: ");
NewStruct = new Struct;
strcpy(NewStruct->text, str);
NewStruct->age = age;
NewStruct->prev= prev;
NewStruct->next= next;
prev->next = NewStruct;
next->prev = NewStruct;
}
void replace_struct_in_list(Struct* ReStruct){
char str[10];
int age;
cout<<"Name: ";
cin.getline(str, 10);
if (cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
age = input("Age: ");
strcpy(ReStruct->text, str);
ReStruct->age = age;
}
Struct* start_new_list(int number) {
Struct* prevStruct = NULL;
Struct* newList = NULL;
for (int counter = 0; counter < number; counter++) {
Struct* newStruct = add_struct_to_list(prevStruct);
if (prevStruct)
prevStruct->next = newStruct;
if (counter == 0)
newList = newStruct;
prevStruct = newStruct;
}
return newList;
}
Struct* find_a_struct(Struct* list_begin, int index){
Struct* node = list_begin->next;
int count = 1;
if (node != NULL) {
while (node->next) {
node = node->next;
count++;
if (count == index) {
break;
}
}
if (count < index) {
node = NULL;
}
}
return node;
}
void add_extra_struct_to_list(Struct* list_begin) {
string command;
Struct* NewStruct = NULL;
int index = input("Enter index of new element (it should be less then 99): ");
Struct* FindedStruct = find_a_struct(list_begin, index);
if (FindedStruct != NULL) {
while (true) {
cout<<"This index is already exist. Replace? (Yes/No): ";
cin>>command;
cout<<endl;
if (command == "Yes" || command == "No") {
break;
}
}
if (command == "No") {
insert_struct_to_list(FindedStruct->prev, FindedStruct);
} else {
replace_struct_in_list(FindedStruct);
}
} else {
NewStruct = add_empty_struct_to_list(list_begin, index);
Struct* ExtraStruct = add_struct_to_list(NewStruct->prev);
NewStruct->next = ExtraStruct;
}
}
void delete_element(Struct* node) {
int index = 0; int count = 1;
bool is_index = false;
do {
index = input("Enter number of index: ");
} while (index <= 0);
do {
node = node->next;
count++;
if (count == index) {
Struct* prevs = 0;
prevs = node->prev;
Struct* nexts = 0;
nexts = node->next;
delete node;
prevs->next = nexts;
nexts->prev = prevs;
is_index = true;
break;
}
} while (node->next);
if (is_index == true) {
cout<<"Done!"<<endl;
} else {
cout<<"Index is out off range!"<<endl;
}
}
void delete_all_list(Struct* list_begin) {
Struct* structToDelete = NULL;
Struct* node = list_begin;
while (node->next) {
structToDelete = node;
node = node->next;
delete structToDelete;
}
delete node;
}
void sort_by_age(Struct* list_begin) {
Struct* node = 0;
Struct* node2 = 0;
int age; char text[10];
for (node = list_begin; node; node = node->next) {
for (node2 = list_begin; node2; node2 = node2->next) {
if (node->age < node2->age) {
strcpy(text, node->text);
strcpy(node->text, node2->text);
strcpy(node2->text, text);
age = node->age;
node->age = node2->age;
node2->age = age;
}
}
}
}
void print_list(Struct* list_begin) {
for (Struct* node = list_begin; node; node = node->next) {
cout<<"Age: "<<node->age<<"; Name: "<<node->text<<endl;
}
}
int main() {
int number;
Struct *NewList = 0;
string command;
bool list = false;
cout<<"\"help\" for more info"<<endl<<endl;
while (true) {
cout<<">>> ";
cin>>command;
cout<<endl;
if (command == "help") {
cout<<"startlist - creating a new double-linked list."<<endl;
cout<<"sortlist - sorting list by age of workers."<<endl;
cout<<"printlist - prining all list's elements."<<endl;
cout<<"addextra - adding extra element to list."<<endl;
cout<<"delete - delete element from list."<<endl;
cout<<"deletelist - delet all list. (Warning: require for create new list!)"<<endl;
cout<<"exit - close program."<<endl;
} else if (command == "startlist") {
if (list == false) {
number = input("Number of worker (it should be less than 99): ");
NewList = start_new_list(number);
cout<<"Done!"<<endl;
list = true;
} else {
cout<<"Error: You allready create one!"<<endl;
}
} else if (command == "sortlist"){
if (list == true) {
sort_by_age(NewList);
cout<<"Done!"<<endl;
} else {
cout<<"Error: You did't create a list or it is already sorted!"<<endl;
}
} else if (command == "printlist") {
if (list == true) {
print_list(NewList);
} else {
cout<<"Error: You did't create a list!"<<endl;
}
} else if (command == "delete") {
if (list == true) {
delete_element(NewList);
} else {
cout<<"Error: You did't create a list!"<<endl;
}
} else if (command == "deletelist") {
if (list == true) {
delete_all_list(NewList);
cout<<"Done!"<<endl;
list = false;
} else {
cout<<"Error: You did't create a list!"<<endl;
}
} else if (command == "addextra") {
if (list == true) {
add_extra_struct_to_list(NewList);
} else {
cout<<"Error: You did't create a list!"<<endl;
}
} else if (command == "exit") {
if (list == true) {
delete_all_list(NewList);
cout<<"Done!"<<endl;
}
break;
} else {
cout<<"Error: There is no such command!"<<endl;
}
cout<<endl;
}
return 0;
}
You have quite a few issues in your program, in the delete_element function your main problem is that you dereference prevs and nexts without checking whether they are NULL.
Adding some simple checks:
if (nexts && prevs)
prevs->next = nexts;
if (prevs && nexts)
nexts->prev = prevs;
Prevents it from segfaulting if any elements are NULL.
Other issues I have found I commented in the live example.
It looks suspicious that count starts from 1 instead 0 in delete_element. Because of this, the first index that your code is able to delete is 2 and you get into trouble if try to delete node 1.
EDIT: And one more thing: deleting the first node and last node needs some special care. For the first node, prev is 0 so you can not say prev->next.