This is what I have so far, but it's not working. Basically skips to else if(cnode == preposition).
void LinkedList::Delete(Node *PrePosition) {
Node *cnode = head;
Node *pnode = NULL;
while (cnode != NULL) {
if (cnode->value != NULL) {
if (pnode == NULL) {
// if there is not previous node
head = cnode->next;
}
else if (cnode == PrePosition) {
// if there is previous node
cout << endl << "Deleting: " << cnode << endl;
pnode->next = cnode->next;
}
}
else {
// don't delete
pnode = cnode;
}
cnode = cnode->next;
}
}
1: Take the pointer from the previous node and point it to the next one after the one you want to delete
2: Delete the pointer from the previous node to the current node
3: Delete the pointer from the next node to the current node (if it is a doubly-linked list)
Three cases of delete in a singly linked-list:
delete the first node
void delete_first()
{
node *temp=new node;
temp=head;
head=head->next;
delete temp;
}
delete the last node
void delete_last()
{
node *current = new node;
node *previous = new node;
current=head;
while(current->next != NULL)
{
previous = current;
current = current->next;
}
tail = previous; // if you have a Node* tail member in your LinkedList
previous->next = NULL;
delete current;
}
delete at a particular position (your case)
void LinkedList::delete_position(int pos)
{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1; i < pos; i++) //or i = 0; i < pos-1
{
previous=current;
current=current->next;
}
previous->next=current->next;
delete current;
}
^^ from codementor ^^
However if your function signature intends delete_node(Node* nodeToDelete) [PrePosition is not a good name in this case] and you want delete the node passed to the function without knowing its position in the list we can modify delete_position() like so:
void LinkedList::delete_node(Node* nodeToDelete)
{
node *current= head;
node *previous= nullptr;
if (head == nodeToDelete){
head = nodeToDelete->next;
delete nodeToDelete;
return
}//else
while(current != nodeToDelete)
{
previous = current;
current = current->next
}
previous->next = current->next;
delete nodeToDelete;
}
Also in your original code, if it's skipping the line you mentioned, pnode is always null when cnode has a non-null value in it.
Here are the full code
class SportShoe {
private:
struct nodeSport {
int ShoeID;
char BrandShoe[SIZE];
char TypeShoe[SIZE];
char ColourShoe[SIZE];
int SizeShoe;
float PriceShoe;
nodeSport *last;
};
nodeSport *first = NULL;
public:
int MenuSportShoe();
void AddSportShoe();
void DisplaySportShoe();
void DeleteSportShoe();
static void ExitSportShoe();
};
int SportShoe::MenuSportShoe() {
int OptionSportShoe = 0;
cout << endl;
cout << "Please select from the menu:" << endl;
cout << ":: 1 :: Add item to shoe list" << endl;
cout << ":: 2 :: Display shoes list" << endl;
cout << ":: 3 :: Delete item from the list" << endl;
cout << ":: 4 :: Back" << endl;
cout << "=>> ";
cin >> OptionSportShoe;
while (OptionSportShoe == 1){
AddSportShoe();
}
while (OptionSportShoe == 2){
DisplaySportShoe();
}
while (OptionSportShoe == 3){
DeleteSportShoe();
}
while (OptionSportShoe == 4){
ExitSportShoe();
}
return 0;
}
void SportShoe::AddSportShoe() {
nodeSport *tempShoe1, *tempShoe2;
tempShoe1 = new nodeSport;
cout << "Please enter the Shoe ID : (eg. 43210) " << endl;
cout << "=>> ";
cin >> tempShoe1->ShoeID;
cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->BrandShoe,SIZE);
cout << "Please enter the Shoe Type : (eg. Running) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->TypeShoe,SIZE);
cout << "What is the Shoe Colour : (eg. Grey) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->ColourShoe,SIZE);
cout << "Please enter Shoe Size : (eg. 9) " << endl;
cout << "=>> ";
cin >> tempShoe1->SizeShoe;
cout << "Please enter the price of the Shoe : (eg. RM123.45) " << endl;
cout << "=>> RM ";
cin >> tempShoe1->PriceShoe;
tempShoe1->last = NULL;
if (first == NULL)
first = tempShoe1;
else
{
tempShoe2 = first;
while (tempShoe2->last != NULL)
tempShoe2 = tempShoe2->last;
tempShoe2->last = tempShoe1;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DisplaySportShoe() {
nodeSport *tempShoe1;
tempShoe1 = first;
while(tempShoe1){
cout << "ID : " << tempShoe1->ShoeID << endl;
cout << "Brand : " << tempShoe1->BrandShoe << endl;
cout << "Type : " << tempShoe1->TypeShoe << endl;
cout << "Colour : " << tempShoe1->ColourShoe << endl;
cout << "Size : " << tempShoe1->SizeShoe << endl;
cout << "Price : " << tempShoe1->PriceShoe << endl;
cout << endl;
tempShoe1 = tempShoe1->last;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DeleteSportShoe(){
nodeSport *tempShoe1, *tempShoe2;
int DataShoe;
tempShoe2 = tempShoe1 = first;
if(tempShoe1 == NULL)
{
cout << "\nList is empty!" << endl;
system("PAUSE");
MenuSportShoe();
}
while(tempShoe1 != NULL)
{
cout << "\nEnter the Shoes ID to be deleted: (eg. 123) ";
cin >> DataShoe;
tempShoe2 = tempShoe1;
tempShoe1 = tempShoe1->last;
if(DataShoe == tempShoe1-> ShoeID){
if(tempShoe1 == first) {
first = first->last;
cout << "\nData deleted ";
}
else{
tempShoe2->last = tempShoe1->last;
if(tempShoe1->last == NULL){
tempShoe2 = tempShoe2;
}
cout << "\nData deleted ";
}
delete(tempShoe1);
system("PAUSE");
MenuSportShoe();
}
else{
cout << "\nRecord not Found!!!" << endl;
system("PAUSE");
MenuSportShoe();
}
}
}
void SportShoe::ExitSportShoe(){
int sepatu;
cout << endl;
cout << "Please choose the option below."<<endl;
cout << ":: 1 :: Sport Shoe." << endl;
cout << ":: 2 :: Ladies High Heel." << endl;
cout << ":: 3 :: Exit" << endl;
cout << "=>> ";
cin >> sepatu;
while(sepatu == 1){
SportShoe listShoe;
listShoe.MenuSportShoe();
}
while(sepatu == 2){
HighHeel listShoe;
listShoe.MenuHighHeel();
}
while(sepatu == 3){
cout << "Thank you. Till we meet again."<< endl;
exit(1);
}
}
main() {
cout << "Hello! Welcome to MySepatu Online Shop administrator."<< endl;
cout << endl;
SportShoe::ExitSportShoe();
HighHeel::ExitHighHeel();
return 0;
}
public class linkedList {
int count = 0;
class Node {
int element;
Node next;
Node(int element) {
this.element = element;
}
}
Node head = null;
Node tail = null;
public void addNode(int Object) {
Node newNode = new Node(Object);
if (head == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void Display() {
Node current = head;
while (current!=null) {
System.out.println(current.element);
count ++;
current = current.next;
}
}
public void Length() {
System.out.println(count);
}
public void Remove(int node) {
Node curr = head;
while (curr!=null) { // looping the nodes
if (curr.element == node ) {
curr.element = curr.next.element;
curr = curr.next;
// To fix the Duplicates
while (curr!= tail) {
curr.element = curr.next.element;
curr = curr.next;
}
RemoveEnd();
break;
}
curr = curr.next;
}
}
public void RemoveEnd() {
Node current3 = head;
while (current3.next != tail) {
current3 = current3.next;
}
tail = current3;
tail.next = null;
}
}
Related
*Create a simple linked list program to create a class list containing
class node {
void *info;
node *next;
public:
node (void *v) {info = v; next = 0; }
void put_next (node *n) {next = n;}
node *get_next ( ) {return next;}
void *get_info ( ) {return info;}
};
Be able to initially fill the list. Provide functions to insert/append nodes and remove nodes from the linked list. Be able to display the contents of the list.
Write a little driver program with at least 5 values passed in (so that 5 nodes are created) as you insert/append, delete and display data, showing the programs operation.
Output: While displaying the data, make sure you use an informational label–using the terms “insert”, “append”, “remove” and any other term which displays the action. All data that is displayed must be displayed in a way in which the mentor can easily read and understand.*
My code runs but it throws Exception thrown: write access violation. this was nullptr. on Line 20 when I debug it. In the output it also stops at Delete 04 of my list and outputs no further data after line 156. I am not sure how to fix this. I tried to force it to output the new list with another cout statement but that did not work. Any assistance would be appreciated. Entire code below.
#include <iostream>
#include <iomanip>
using namespace std;
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) break;
previous = temp;
temp = temp->get_next();
}
previous->put_next(temp->get_next());
delete temp;
}
}
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
SOLUTION:
//Node.h
#pragma once
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
//List.h
#pragma once
#include "Node.h"
#include <iomanip>
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
//List.cpp
#include <iostream>
#include "List.h"
using namespace std;
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) {
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}
}
//Main.cpp
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
So whenever you are deleting first node, you missed to set the head to the next node of head.
Commented at the parts which are modified in the else statement of DELETE function
Code:
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info){
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}
I have to create a doubly linked list that can store different types of data (in fact, I need to make a small program in which the name of the plant, plant class, plant family will be stored). In general, I already made a doubly-linked list, but earlier only decimal numbers were stored there. When I wanted to store whole sentences instead of numbers - there was a problem.
here is an example code:
(and yes, I'm a foreign student, and our teachers require comments in our native language, so sorry for the inconvenience)
#include <iostream>
#include <list>
#include <locale>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
//template <typename A>//создаем тип
typedef struct Node // создание узла двусвязного списка
{
public:
char plant[100]; //информационое поле
Node* Next, * Prev; //указатели на адреса началаспискаи конца
};
class List // создаемтип данных список
{
Node* Head;
public:
List() {
Head = NULL; // изначально список пустой
}
void create(char x);
void show();
void add_begin(char x);
void add_end(char x);
void add_after(char x, int position);
void delete_(char x);
};
void List::create(char x) // функция создания листа, поочерёдно добавляя элементы
{
if (Head != NULL) {// если списщк не пустой- возращаемся
cout << "The list already created." << endl;
return;
}
else {
//Node* h, * temp;
Node* temp = new Node;
Node* h = new Node;
temp = new(Node);
temp->plant = x;
temp->Next = NULL;
temp->Prev = NULL;
Head = temp;
cout << "action completed" << endl;
}
}
void List::add_end(char x)
{
Node* temp = new(Node); // создаем новый елемент ,
temp->Next = NULL; // следующего елемента нет
temp->plant = x; // заполняем данные
if (Head == NULL) // если список пустой - добавляем первый элемент в список
{
temp->Prev = NULL;
Head = temp;
}
else {
Node* h = Head;
while (h->Next != NULL)
h = h->Next;
h->Next = temp;
temp->Prev = h;
}
cout << "action completed" << endl;
}
void List::add_begin(char x)
{
Node* temp = new(Node); // создание нового узла, выставление ссылок
temp->Prev = NULL; // предыдущего елемента не существует
temp->plant = x; // заполняем данные
temp->Next = Head; // следующий елемент - бывший head
if (Head == NULL) // если список пустой- то добавляем первый елемент
{
temp->Prev = NULL;
Head = temp;
}
else {
Head->Prev = temp;
Head = temp;
}
cout << "action completed" << endl; // действие выполнено
}
void List::add_after(char x, int y)
{
if (Head == NULL) // есть ли один узел?
{
cout << "First сreate the list." << endl;
return;
}
Node* tmp, * h = Head;
for (int i = 0; i < y - 1; i++)
{
h = h->Next;
if (h == NULL) // проверка, есть ли элемент в списке
{
cout << "There are less than " << y << " elements." << endl;
return;
}
}
tmp = new(Node); // создание нового узла
tmp->plant = x; // заполняем данные
if (h->Next == NULL) // если послн елемента - ноль , то указатели выставлчем длч следующего елемента
{
h->Next = tmp;
tmp->Next = NULL; // слудующего елемента не существует
tmp->Prev = h; // предидущий - голова
}
else // если после елемента не идет ноль то тоже выставляем соответствующие указатели
{
tmp->Next = h->Next;
tmp->Next->Prev = tmp;
h->Next = tmp;
tmp->Prev = h;
}
cout << "action completed" << endl;
}
void List::delete_(char x)
{
Node* tmp, * h;
if (Head == NULL) // емли нет не одного узла, то возращаемся
{
cout << "List empty,nothing to delete" << endl;
return;
}
if (Head->plant == x) //удаляем первый елемент
{
tmp = Head;
Head = Head->Next; // теперь голова -это следующий елемент
Head->Prev = NULL; // предыдущего не существует
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = Head;
while (h->Next->Next != NULL)
{
if (h->Next->plant == x) // удаляем елемент после
{
tmp = h->Next;
h->Next = tmp->Next;
tmp->Next->Prev = h;
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = h->Next;
}
if (h->Next->plant == x) // удаление последнего елемента
{
tmp = h->Next;
free(tmp);
h->Next = NULL; //следующего не существует
cout << "Element Deleted" << endl;
return;
}
cout << "Element " << x << " not found" << endl;
}
void List::show()
{
Node* h = Head;
if (Head == NULL) // если нет не одного узла, то возращаемся
{
cout << "List empty,nothing to display" << endl;
return;
}
cout << "The Doubly Link List is :" << endl;
while (h != NULL) //пока голова не будет равняться нулю роказывать даные
{
cout << h->plant << endl;
h = h->Next;
}
}
int main()
{
setlocale(LC_ALL, "ukr");
int choice, position;
char element;
List b;
while (222)
{ //действия которые можно использовать
cout << "****" << endl;
cout << "1(Створити список)" << endl;
cout << "2(Додати елемент в початок)" << endl;
cout << "3(Додати елемент в кiнець)" << endl;
cout << "4(Додати пiсля елемента)" << endl;
cout << "5(Видалити)" << endl;
cout << "6(Показати список)" << endl;
cout << "7(Вийти)" << endl;
cout << " Вибершть дiю : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Введiть значення: ";
cin >> element;
b.create(element);
cout << endl;
break;
case 2:
cout << "Введiть значення: ";
cin >> element;
b.add_begin(element);
cout << endl;
break;
case 3:
cout << "Введiть значення: ";
cin >> element;
b.add_end(element);
cout << endl;
break;
case 4:
cout << "Введiть значення: ";
cin >> element;
cout << "Введiть елемент пiсля якого додати: ";
cin >> position;
b.add_after(element, position);
cout << endl;
break;
case 5:
cout << "Введiть елемент для значення: ";
cin >> element;
b.delete_(element);
cout << endl;
break;
case 6:
b.show();
cout << endl;
break;
case 7:
cout << "Завершення" << endl;
exit(222);
}
}
return 0;
}
below is my current in-progress code converting a singly linked to a doubly linked list. I haven't touched the delete function yet. I've gotten insert in empty list, end of list, and beginning of list apparently working.
However nodes inserting in the middle seemingly fail to create a link to the previous node. My debugging lines I inserted seem to show both the n->next and n-> prev with the correct memory address, but when I go to reverseprint, any nodes inserted in the middle are missed and the links are gone. Where am I going wrong in regards to this?
Code below:
#include <iostream>
#include <string>
using namespace std;
// define a node for storage and linking
class node {
public:
string name;
node *next;
node *prev;
};
class linkedList {
public:
linkedList() :top(NULL) {}
bool empty() { return top == NULL; }
node *getTop() { return top; }
node *getEnd() { return end; }
void setTop(node *n) { top = n; }
void setEnd(node *p) { end = p; }
void add(string);
int menu();
void remove(string);
~linkedList();
void reversePrint();
friend ostream& operator << (ostream&, const linkedList&); // default output is in-order print.
private:
node *top;
node *end;
};
void main() {
linkedList l;
cout << l.empty() << endl;
int option = 0;
string s;
bool go = true;
while (go) {
option = l.menu();
switch (option) {
case 1: cout << "enter a name: "; cin >> s; l.add(s); break;
case 2: cout << "enter name to be deleted: "; cin >> s; l.remove(s); break;
case 3: cout << l; break;
//case 4: cout << "can not be done with a singly linked list" << endl;
case 4: l.reversePrint(); break;
case 5: cout << "exiting" << endl; go = false; break;
}
}
system("pause");
}
void linkedList::remove(string s) {
bool found = false;
node *curr = getTop(), *prev = NULL;
while (curr != NULL) {
// match found, delete
if (curr->name == s) {
found = true;
// found at top
if (prev == NULL) {
node *temp = getTop();
setTop(curr->next);
delete(temp);
// found in list - not top
}
else {
prev->next = curr->next;
delete(curr);
}
}
// not found, advance pointers
if (!found) {
prev = curr;
curr = curr->next;
}
// found, exit loop
else curr = NULL;
}
if (found)cout << "Deleted " << s << endl;
else cout << s << " Not Found " << endl;
}
void linkedList::add(string s) {
node *n = new node();
n->name = s;
n->next = NULL;
n->prev = NULL;
// take care of empty list case
if (empty()) {
top = n;
end = n;
// take care of node belongs at beginning case
}
else if (getTop()->name > s) {
n->next = getTop();
n->prev = NULL;
setTop(n);
node *temp;
temp = n->next;
temp->prev = n;
// take care of inorder and end insert
}
else {
// insert in order case
node *curr = getTop(), *prev = curr;
while (curr != NULL) {
if (curr->name > s)break;
prev = curr;
curr = curr->next;
}
if (curr != NULL) { // search found insert point
n->next = curr;
cout << n->name << " " << n << " prev " << prev << " " << prev->name << endl;
n->prev = prev;
prev->next = n;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
cout << "n->next is: " << n->next << " " << n->next->name << endl;
}
// take care of end of list insertion
else if (curr == NULL) {// search did not find insert point
prev->next = n;
n->prev = prev;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
setEnd(n);
}
}
}
ostream& operator << (ostream& os, const linkedList& ll) {
//linkedList x = ll; // put this in and the code blows up - why?
node *n = ll.top;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
os << n->name << endl;
os << n << endl;
if (n->next != NULL) {
os << "next is " << n->next << endl;
}
n = n->next;
}
return os;
}
void linkedList::reversePrint() {
node *n = end;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
//cout << n->name << endl;
cout << "memory address of " << n->name << " is " << n << endl;
if (n->prev != NULL) {
cout << "prev is " << n->prev << endl;
}
n = n->prev;
}
return;
}
// return memory to heap
linkedList::~linkedList() {
cout << "~linkedList called." << endl;
node *curr = getTop(), *del;
while (curr != NULL) {
del = curr;
curr = curr->next;
delete(del);
}
}
int linkedList::menu() {
int choice = 0;
while (choice < 1 || choice > 5) {
cout << "\nEnter your choice" << endl;
cout << " 1. Add a name." << endl;
cout << " 2. Delete a name." << endl;
cout << " 3. Show list." << endl;
cout << " 4. Show reverse list. " << endl;
cout << " 5. EXIT " << endl;
cin >> choice;
}
return choice;
}
You are not setting the prev of the current in insertion into middle, just do:
n->next = curr;
curr->prev = n; // <-- this
Need a void function Display that will display the binary search tree in tree shape
Need a value return or void function Search that will search for a specific data.
Not really sure What to do from this point except trial and error and trying to read off of others code...
I need help
Help
Here is my code...
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const { return root == NULL; }
void print_inorder();
void inorder(tree_node*);
void print_preorder();
void preorder(tree_node*);
void print_postorder();
void postorder(tree_node*);
void insert(int);
void remove(int);
bool Search(int, tree_node*);
void Display(tree_node*, int);
};
int main()
{
BinarySearchTree b;
int ch, tmp, tmp1;
while (1)
{
system("cls");
cout << endl << endl;
cout << " Binary Search Tree Operations " << endl;
cout << " ----------------------------- " << endl;
cout << " 1. Insertion/Creation " << endl;
cout << " 2. In-Order Traversal " << endl;
cout << " 3. Pre-Order Traversal " << endl;
cout << " 4. Post-Order Traversal " << endl;
cout << " 5. Removal " << endl;
cout << " 6. Display " << endl;
cout << " 7. Display Message From Creator " << endl;
cout << " 8. EXIT " << endl;
cout << " Enter your choice : ";
cin >> ch;
switch (ch)
{
case 1: cout << " Enter Number to be inserted : ";
cin >> tmp;
b.insert(tmp);
break;
case 2: cout << endl;
cout << " In-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_inorder();
break;
case 3: cout << endl;
cout << " Pre-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_preorder();
break;
case 4: cout << endl;
cout << " Post-Order Traversal " << endl;
cout << " --------------------" << endl;
b.print_postorder();
break;
case 5: cout << " Enter data to be deleted : ";
cin >> tmp1;
b.remove(tmp1);
break;
case 6: cout << " Enter data to be deleted : ";
b.Display(NULL, tmp);
break;
case 7: cout << " I think you are a great person. Smile be happy ";
case 8:
return 0;
}
}
}
bool BinarySearchTree::Search(int d, tree_node* curr){
if (curr == NULL) {
return 0;
}
if (curr->data == d) {
return 1;
}
if (d > curr->data) {
return Search(d, curr->right);
}
else {
return Search(d, curr->left);
}
}
// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if (isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while (curr)
{
parent = curr;
if (t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if (t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
void BinarySearchTree::remove(int d)
{
//Locate the element
bool found = false;
if (isEmpty())
{
cout << " This Tree is empty! " << endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while (curr != NULL)
{
if (curr->data == d)
{
found = true;
break;
}
else
{
parent = curr;
if (d>curr->data) curr = curr->right;
else curr = curr->left;
}
}
if (!found)
{
cout << " Data not found! " << endl;
return;
}
// 3 cases :
// 1. We're removing a leaf node
// 2. We're removing a node with a single child
// 3. we're removing a node with 2 children
parent = NULL;
// Node with single child
if ((curr->left == NULL && curr->right != NULL) || (curr->left != NULL
&& curr->right == NULL))
{
if (curr->left == NULL && curr->right != NULL)
{
if (parent->left == curr)
{
parent->left = curr->right;
delete curr;
}
else
{
parent->right = curr->right;
delete curr;
}
}
else // left child present, no right child
{
if (parent->left == curr)
{
parent->left = curr->left;
delete curr;
}
else
{
parent->right = curr->left;
delete curr;
}
}
return;
}
//We're looking at a leaf node
if (curr->left == NULL && curr->right == NULL)
{
if (parent->left == curr) parent->left = NULL;
else parent->right = NULL;
delete curr;
return;
}
//Node with 2 children
// replace node with smallest value in right subtree
if (curr->left != NULL && curr->right != NULL)
{
tree_node* chkr;
chkr = curr->right;
if ((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
delete chkr;
curr->right = NULL;
}
else // right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element
if ((curr->right)->left != NULL)
{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while (lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
void BinarySearchTree::print_inorder()
{
inorder(root);
}
void BinarySearchTree::inorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) inorder(p->left);
cout << " " << p->data << " ";
if (p->right) inorder(p->right);
}
else return;
}
void BinarySearchTree::print_preorder()
{
preorder(root);
}
void BinarySearchTree::preorder(tree_node* p)
{
if (p != NULL)
{
cout << " " << p->data << " ";
if (p->left) preorder(p->left);
if (p->right) preorder(p->right);
}
else return;
}
void BinarySearchTree::print_postorder()
{
postorder(root);
}
void BinarySearchTree::postorder(tree_node* p)
{
if (p != NULL)
{
if (p->left) postorder(p->left);
if (p->right) postorder(p->right);
cout << " " << p->data << " ";
}
else return;
}
void BinarySearchTree::Display(tree_node *curr, int indent)
{
if (curr != NULL)
{
cout << "My Tree. The left is top and right is bottom" << endl;
Display(curr->left, indent + 4);
if (indent > 0)
cout << setw(indent) << " ";
cout << curr->data << endl;
Display(curr->right, indent + 4);
}
}
I need to find the largest element in the list. In the following code unsubscribed items and ordered them. How to find the last element of list? I think that I need add one more function void maksimum(), but I'm having trouble with that.
#include <iostream>
#include <string>
#include <time.h>
#include <conio.h>
#include <cstdlib>
using namespace std;
struct element
{
int number;
element* next;
element();
};
element::element()
{
next = NULL;
}
struct list
{
element* first;
void fill_list(int number);
void segregate();
void show_list();
void maksimum();
list();
};
list::list()
{
first = NULL;
}
void list::fill_list(int number)
{
element *nowy = new element;
nowy->number = number;
if(first == 0)
{
first = nowy;
}
else
{
element* temp = first;
while(temp->next)
{
temp = temp->next;
}
temp->next = nowy;
}
}
void list::show_list()
{
element* temp = first;
if(temp == 0)
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while(temp)
{
cout << temp->number << endl;
temp = temp->next;
}
cout << "the smallest element: : " << first->number << endl;
if(first->next == 0)
{
cout << "Largest element = Smallest element :)" << endl;
}
}
}
void list::segregate()
{
element* new_first = NULL;
element* prv;
element* temp;
element* maks;
while(first)
{
maks = first;
prv = NULL;
temp = first;
while(temp->next)
{
if(temp->next->number > maks->number)
{
prv = temp;
maks = temp->next;
}
temp=temp->next;
}
if (prv)
{
prv->next = maks->next;
}
else
{
first = maks->next;
}
maks->next = new_first;
new_first = maks;
}
first = new_first;
}
int main()
{
int n=0;
int number=0;
list* base = new list;
cout << "Size of list: " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "No " << i+1 << ": ";
cin >> number;
base->fill_list(number);
}
base->segregate();
base->show_list();
//base->maksimum();
delete(base);
return 0;
}
How can I do that?
ok. you're right, but I thought that my code shows my work. not matter :)
i solved my problem. My function: ^^
void list::show_list()
{
element * temp = first;
if( temp == 0 )
{
cout << "List is empty." << endl;
cout << "No smallest element " << endl;
cout << "No largest element" << endl;
}
else
{
while( temp->next != 0 )
{
temp = temp->next;
}
cout << "The largest element: " << temp->number << endl;
cout << "The smallest element: " << first->number << endl;
}
}