I have this task to do. Basically, I have to create a dynamic stack, then I have to choose an element and swap it with a new one which I inserted. The other elements remain the same and I have to display the new data. I've come to a dead end.
#include <iostream>
using namespace std;
struct elem
{
int key;
elem* next;
} *start = NULL, *p;
void push(int n);
int pop(int &n);
int main()
{
int num, counter = 0;
do
{
cout << "Input integers(!=0): ";
cin >> num;
if (num > 0 || num < 0)
{
push(num);
counter++;
}
}
while (num != 0);
cout << "\nStack: ";
while (pop(num))
cout << num << "\t";
cout << "\n";
int element, newValue;
cout << "Input element number: ";
cin >> element;
cout << "New value of element: ";
cin >> newValue;
here I struggle doing the swap
return 0;
}
void push(int n)
{
p = start;
start = new elem;
start->key = n;
start->next = p;
}
int pop(int &n)
{
if (start)
{
n = start->key;
p = start;
start = start->next;
delete p;
return 1;
}
else
return 0;
}
How do you swap a chosen one from a stack of (dinner) plates with the top one?
you pick the topmost, put it aside, then pick all the ones you don't want and put them on a new stack until you reach the chosen one. Pick it, exchange it with the original topmost one, put the chosen one aside.
Then re-stack, one by one, the plates from the new stack to the old one. Lastly, put the one you put aside on top.
Going through an intermediary stack like #Bathsheba suggested is the most straight forward solution here.
You can also save some execution time by simply modifying the "next" var of the previous
element to the element you're going the change.
#include <iostream>
using namespace std;
struct elem
{
int key;
elem* next;
}
*start = NULL, *p,*previous,*curr,*temp;
void push(int n);
int pop(int &n);
int main() {
int num, counter = 0;
do {
cout << "Input integers(!=0): ";
cin >> num;
if (num > 0 || num < 0) {
push(num);
counter++;
}
}
while (num != 0);
/* cout << "\nStack: ";
while (pop(num))
cout << num << "\t";
cout << "\n";
*/
int element, newValue;
cout << "Input element number: ";
cin >> element;
cout << "New value of element: ";
cin >> newValue;
curr = start ;
previous = NULL;
while(curr->next)
{
if(curr->key == element){
if(previous) {
temp = new elem;
temp->key = newValue;
temp->next = curr->next ;
previous->next = temp ;
break;
}
else {
temp = new elem;
temp->key = newValue;
temp->next = curr->next ;
start = temp ;
break;
}
}
else {
previous = curr ;
curr = curr->next;
}
}
while (pop(num))
cout << num << "\t";
cout << "\n";
return 0;
}
void push(int n) {
p = start;
start = new elem;
start->key = n;
start->next = p;
}
int pop(int &n) {
if (start) {
n = start->key;
p = start;
start = start->next;
delete p;
return 1;
}
else
return 0;
}
Related
A Bank manager want to segregate different Currency notes in to 3 different baskets. Initially, all the currencies are in one Basket and the currencies are USD, INR and EUR. Now, you are supposed to write a program that can segregate the currencies to 3 different buckets. While, segregation, make sure to have a track of the overall sum of the currencies in terms of INR for each basket.
Program Requirements:
1.First get the input from the user for the overall Basket. [Even numbers are mapped as USD, Odd numbers are mapped as INR and Prime numbers are mapped as EUR, if there is an intersection, you are free to select any one of them]
2.After receiving the elements of the Basket, try a function to segregate the currencies
3.While adding the currency to its corresponding basket, ensure to calculate the overall sum.
4.Whenever, the bank manager wants to see the basket, you should display all the baskets and its corresponding SUM, MEAN, MEDIAN and MODE.
5.Also, there should be a provision to remove required amount of currency in each basket. [While removal, you need to enter the amount of removal in INR and its corresponding value should be removed from the respective basket]
NOTE: Use the value, USD = 73 INR and EUR = 86.5 INR
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int prime(int n);
struct node
{
int info;
struct node *next;
}*last;
class circular_llist
{
public:
void insert(int value);
void delete_element(int value);
void display_list();
circular_llist()
{
last = NULL;
}
};
int main()
{
int element, choice, ch;
int arr[100], i, n, x;
int sum_usd=0, sum_inr=0, sum_eur=0;
int c_usd=0, c_inr=0, c_eur=0;
int arr_usd[n], arr_inr[n], arr_eur[n];
cout << "Enter the total number of elements" << endl;
cin >> n;
cout << "Enter the elements:" << endl;
for(i=0;i<n;i++) {
cin >> x;
arr[i]=x;
}
circular_llist usd;
circular_llist inr;
circular_llist eur;
for(i=0;i<n;i++) {
if(prime(arr[i])==1) {
eur.insert(arr[i]);
sum_eur+=arr[i];
c_eur++;
}
else if(arr[i]%2==0) {
usd.insert(arr[i]);
sum_usd+=arr[i];
c_usd++;
} else {
inr.insert(arr[i]);
sum_inr+=arr[i];
c_inr++;
}
}
do{
cout << "1.Delete Element" << endl;
cout << "2.Display elements" << endl;
cout << "3.Show mathematical figures" << endl;
cout << "4.Quit" << endl;
cin >> ch;
switch(ch)
{
case 1:
cout << "From which basket do you want to delete?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
usd.delete_element(element);
cout<<endl;
break;
case 2:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
inr.delete_element(element);
cout<<endl;
break;
case 3:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
eur.delete_element(element);
cout<<endl;
break;
}
case 2:
cout << "From whick basket do you want to diplay thye elements?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
usd.display_list();
cout << endl;
break;
case 2:
inr.display_list();
cout << endl;
break;
case 3:
eur.display_list();
cout << endl;
break;
}
case 3:
cout << "For which basket do you want tp show the mathematical figures?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "Sum = " << sum_usd << endl;
cout << "Mean = " << endl;
case 2:
cout << "Sum = " << sum_inr << endl;
case 3:
cout << "Sum = " << sum_eur << endl;
}
case 4:
cout << "EXIT" << endl;
break;
default :
cout << "Choose a valid option" << endl;
break;
}
}while(ch!=4);
return 0;
}
/*
* Create Circular Link List
*/
void circular_llist::insert(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
/*
* Deletion of element from the list
*/
void circular_llist::delete_element(int value)
{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}
/*
* Display Circular Link List
*/
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
/*
*Check in the element is prime or not
*/
int prime(int n) {
int i;
int a;
for(i=2;i<n;i++){
if(n%i==0) {
a = 0;
break;
}
}
return a;
}
Change this: int arr_usd[n], arr_inr[n], arr_eur[n];
Into this: int arr_usd[20], arr_inr[20], arr_eur[20];
or any other number other than 20. It shows an error as n value hasn't been initialised yet.
Done completely using LinkedList in C
#include <stdio.h>
#include <stdlib.h>
struct Node{
float data;
struct Node* next;
};
struct Node *EUR=NULL;
struct Node *USD=NULL;
struct Node *INR=NULL;
void sort(struct Node **h){
struct Node* node1;
struct Node* node2;
int temp;
for(node1=*h;node1!=NULL;node1=node1->next){
for(node2=node1->next;node2!=NULL;node2=node2->next){
if(node1->data>node2->data){
temp = node1->data;
node1->data = node2->data;
node2->data = temp;
}
}
}
}
void add(float val,struct Node **h){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = val;
temp->next = NULL;
if(*h==NULL){
*h = temp;
return;
}
struct Node *node = *h;
while(node->next!=NULL){
node = node->next;
}
node->next = temp;
}
void delete(struct Node** h, float amt){
struct Node *node = *h;
if(*h!=NULL){
if(node->data==amt){
*h = node->next;
}else{
int flag=0;
while(node->next!=NULL){
if(node->next->data==amt){
node->next = node->next->next;
flag=1;
printf("[*]Amount removed\n");
break;
}
node = node->next;
}
if(!flag){
printf("[*]Amount not in Basket!!!\n");
}
}
}else{
printf("[*]Failed\tZero Balance\n");
}
}
float sum(struct Node** h){
if(*h==NULL)
return 0;
float s=0;
struct Node *node = *h;
while(node!=NULL){
s += node->data;
node = node->next;
}
return s;
}
float mean(struct Node** h){
if(*h==NULL)
return 0;
int l=0;
float m,s=0;
struct Node *node = *h;
while(node!=NULL){
l++;
s += node->data;
node = node->next;
}
m =s/l;
return m;
}
float median(struct Node** h){
if(*h==NULL)
return -1;
float med;
struct Node* f_node = *h;
struct Node* p_node = *h;
struct Node* s_node = *h;
while(f_node!=NULL && f_node->next!=NULL){
f_node = f_node->next->next;
p_node = s_node;
s_node = s_node->next;
}
if(f_node!=NULL){//odd
med = s_node->data;
}else{
med = (p_node->data+s_node->data)/2;
}
return med;
}
int mode(struct Node **h){
if(*h==NULL)
return 0;
int max_value=0;
int count,max_count = 0;
struct Node *node = *h;
while (node!=NULL){
count = 0;
struct Node *node2 = node->next;
while(node2!=NULL){
if(node->data==node2->data)
count++;
node2 = node2->next;
}
if(count>max_count){
max_value = node->data;
max_count = count;
}
node = node->next;
}
if(max_count==0)
return 0;
return max_value;
}
void print(struct Node** h,char *m){
printf("printing %s>>>\n",m);
if(*h==NULL){
printf("[*]No bills\n");
return;
}
struct Node* node = *h;
while(node->next!=NULL){
printf("%.2f->",node->data);
node = node->next;
}
printf("%.2f\n",node->data);
printf("[*]SUM: %.2f\n",sum(h));
printf("[*]MEAN: %.2f\n",mean(h));
printf("[*]MEDIAN: %.2f\n",median(h));
printf("[*]MODE: %d\n",mode(h));
}
int even(int n){
if(n%2==0)
return 1;
return 0;
}
int prime(int n){
for(int i=2;i<=n/2;i++){
if(n%i==0){
return 0;
}
}
return 1;
}
int main(){
int n;
int num;
printf("Enter total no of bills: ");
scanf("%d",&n);
float eur = 86.5f;
float usd = 73.0f;
for(int i=0;i<n;i++){
printf("Enter bill %d: ",i+1);
scanf("%d",&num);
if(prime(num))
add(eur*num,&EUR);
else if(even(num))
add(usd*num,&USD);
else
add((float)num,&INR);
}
sort(&EUR);
sort(&USD);
sort(&INR);
int ch1,ch2,br=0;
float amt;
while(1){
printf("1.Display Baskets\n2.Delete Amount\n3.Quit\nEnter your choice: ");
scanf("%d",&ch1);
switch(ch1){
case 1:
print(&EUR,"EURO");
print(&USD,"USD");
print(&INR,"INR");
break;
case 2:
printf("Enter amount to be deleted: ");
scanf("%f",&amt);
printf("Delete From>>>\n1.EUR\t2.USD\t3.INR");
scanf("%d",&ch2);
switch(ch2){
case 1:
delete(&EUR,amt);
break;
case 2:
delete(&USD,amt);
break;
case 3:
delete(&INR,amt);
break;
default:
printf("[*]Wrong Input\n");
break;
}
break;
default:
br = 1;
break;
}
if(br)
break;
}
}```
The following code calculates the sum of the elements of the unidirectional list items greater than 3 and smaller than 8 and the result of the sum is changed the beginning of the list.
#include <iostream>
using namespace std;
struct List
{
int num;
List* nItem;
};
int Input()
{
int number;
cout << "Enter the number: "; cin >> number;
return number;
}
void MakeList(List **head, int n)
{
if (n > 0) {
*head = new List;
(*head)->num = Input();
(*head)->nItem = NULL;
MakeList(&(*head)->nItem, n - 1);
}
}
void Print(List* head)
{
if (head != NULL) {
cout << head->num << " ";
Print(head->nItem);
}
}
List* Add_start(List* head, int index, int elm)
{
List* p = new List;
p->num = elm;
p->nItem = NULL;
if (head == NULL) {
head = p;
}
else {
List* current = head;
for (int i = 0; (i < index - 1) && (current->nItem != NULL); i++)
{
current = current->nItem;
}
if (index == 0)
{
p->nItem = head;
head = p;
}
else {
if (current->nItem != NULL) {
p->nItem = current->nItem;
}
current->nItem = p;
}
}
return head;
}
int Sum(List* head)
{
int sum = 0;
List* p = head;
while(p) {
if ((p->num > 3) && (p->num < 8))
sum += p->num;
p = p->nItem;
}
return sum;
}
void DeleteList(List* head)
{
if (head != NULL) {
DeleteList(head->nItem);
delete head;
}
}
int main()
{
int n = 10;
List* head = NULL;
cout << "Enter 10 number to the list\n" << endl;
MakeList(&head, n);
int sum = Sum(head);
head = Add_start(head, 0, sum);
cout << "\nList: ";
Print(head);
cout << endl;
DeleteList(head);
system("pause");
return 0;
}
How can I do the same operation with a bidirectional list?
Notes:
A bidirectional (or double linked) list, also has a member pointing to the previous node: this is the whole difference between the 2 list types (as a consequence the first element - or the one at the left of the list, will have this member pointing to NULL). So, when such a node is created/inserted into a list, this new member should be set as well (I commented in the code places where this happens), for the new node and for the one following it (if any).
I modified the way of how a list is created - MakeList replaced by _MakeList2 + MakeList2; the underscore(_) in _MakeList2 specifies that it's somehow private (convention borrowed from Python) - it's not very nice, but I thought it's easier this way
I don't have Visual Studio on this computer, so I used gcc. It complained about system function so I had to add #include <stdlib.h>
I renamed some of the identifiers (List -> Node, Add_start -> AddNode, nItem -> nNode) either because the new names make more sense, or their names are consistent
I tried to keep the changes to a minimum (so the solution is as close as possible to your original post)
I enhanced (by adding an additional argument: toRight (default value: 1)) the Print func, so it can iterate the list both ways - I am iterating right to left (for testing purposes) before deleting the list
I corrected some (minor) coding style issues
Here's the modified code:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Node {
int num;
Node *pNode, *nNode; // Add a new pointer to the previous node.
};
int Input() {
int number;
cout << "Enter the number: "; cin >> number;
return number;
}
Node *_MakeList2(int n, Node *last=NULL) {
if (n > 0) {
Node *node = new Node;
node->num = Input();
node->pNode = last;
node->nNode = _MakeList2(n - 1, node);
return node;
}
return NULL;
}
Node *MakeList2(int n) {
return _MakeList2(n);
}
void Print(Node *head, int toRight=1) {
if (head != NULL) {
cout << head->num << " ";
if (toRight)
Print(head->nNode, 1);
else
Print(head->pNode, 0);
}
}
Node* AddNode(Node *head, int index, int elm) {
Node *p = new Node;
p->num = elm;
p->pNode = NULL; // Make the link between this node and the previous one.
p->nNode = NULL;
if (head == NULL) {
head = p;
} else {
Node *current = head;
for (int i = 0; (i < index - 1) && (current->nNode != NULL); i++) {
current = current->nNode;
}
if (index == 0) {
p->nNode = head;
head->pNode = p; // Make link between next node's previous node and the current one.
head = p;
} else {
if (current->nNode != NULL) {
p->nNode = current->nNode;
}
p->pNode = current; // Make the link between this node and the previous one.
current->nNode = p;
}
}
return head;
}
int Sum(Node* head) {
int sum = 0;
Node *p = head;
while(p) {
if ((p->num > 3) && (p->num < 8))
sum += p->num;
p = p->nNode;
}
return sum;
}
void DeleteList(Node *head) {
if (head != NULL) {
DeleteList(head->nNode);
delete head;
}
}
int main() {
int n = 10;
Node *head = NULL, *tail = NULL;
cout << "Enter " << n << " number(s) to the list" << endl << endl;
head = MakeList2(n);
int sum = Sum(head);
head = AddNode(head, 0, sum);
cout << endl << "List: ";
Print(head);
cout << endl;
tail = head;
if (tail) {
while (tail->nNode != NULL)
tail = tail->nNode;
cout << endl << "List reversed: ";
Print(tail, 0);
cout << endl;
}
DeleteList(head);
system("pause");
return 0;
}
Example:
Linked List A: 1->2->3
Linked List B: 4->5->6
My task is to make a function, that passes List B into List A at any given position (n).
For instance: After "2" = 1->4->5->6->2->3 (output).
I wasn't really sure, how to do this, so I used:
// Function that finds a number in a list and gets an address of that node.
Node* List::find(int i)
{
for (start();!end();next())
if(current->num==i) return current;
return NULL;
};
// Function, that puts freely desired number at position n in the list;
Example cin >> i; // i = 6;
1->2->6->desired number->...
Node* List::addAfter(int pos, int num)
{
Node* p = NULL; i
current = find(pos);
if (current != NULL)
{
p = new Node(num);
p->next = current->next;
current->next = p;
}
if (last == current) last = p;
current = p;
return p;
}
Both things works, but only as:
cout << "After which number?" << endl;
cin >> i; // **2**
l.addAfter(i, 1); // Before: 2->3->4 After: 2->1->3->4
l.print();
This works perfectly! But if I have two lists - l1 (2->3->4 and l2 6->7)
how can I put both together using this function?
Node* List::addAfter(int pos, I HAVE TO PASS L2 VALUES HERE)
How can I give this function l2 values as parameter?
Is there maybe a better way, to do this? I'd appreciate any help.
WHOLE CODE:
#include <iostream>
using namespace std;
class Node
{
public:
int num;
Node *next;
Node (int n) { num = n; next = NULL; };
};
class List
{
protected:
Node *first, *last;
public:
Node *current;
public:
List () { first = last = current = NULL; };
void add_element (int n);
void delete_element ();
void print(); // Izdrukā sarakstu
bool is_empty () { return (first == NULL); };
void start () { current = first; };
bool end () { return (current == NULL); };
void next(){if (!end())current = current -> next;};
Node* find(int i);
Node* addAfter(int i, List * l2);
~List();
};
int main()
{
List l, l2;
int k, i;
cout << "Type number: (0,to stop):\n";
cin >> k;
while (k!=0)
{
l.add_element (k);
cout << "Type number: (0, to stop):\n";
cin >> k;
};
cout << endl;
cout << "Type 2nd list numbers: (0,to stop):\n";
cin >> k;
while (k!=0)
{
l2.add_element (k);
cout << "Type 2nd list numbers: (0,to stop):\n";
cin >> k;
};
cout << endl;
l.print();
l2.print();
cout << "After which element do you want to insert second list?" << endl;
cin >> i;
l.addAfter(i, l2); // GETTING ERROR HERE.
l.print();
return 0;
}
simplest and easiest form is to pour out both stacks into an array
const int size = stackA.size() + stackB.size();
const stackASize = stackA.size();
const stackBSize = stackB.size();
int arrayOfStackA [size];
int arrayOfStackB [stackBSize];
//Pop StackA into ArrayA
for(int i=stackASize-1; i>0; i++)
{
arrayOfStackA[i] = stackA.pop();
}
//Pop StackB into ArrayB
for(int i=stackBSize-1; i>=0; i++)
{
arrayOfStackB[i] = stackB.pop();
}
Now find the index where you want to insert the data in array A.
In your case you want to enter stack b after 1 which in case of array is the index:1
int count = 0
for(int i=0;i<size;i++){
if(i<requiredIndexNumber){
//do nothing
}
else if(i>=requiredIndexNumber && count!=stackBSize){
int temp = arrayOfStackA[i];
arrayOfStackA[i] = arrayOfStackB[count++];
arrayOfStackA[stackASize+i] = temp;
}
}
This is the most easiest from of popping one stack into an other at any index
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++.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Here is my code. The problem that I am getting is that I can't make work the deleter part. I want to delete one element of the structure. Here is a basic structure that you add, search and delete elements that are added. Also the elements are sorted in increasing order.
#include <iostream>
using namespace std;
struct el {
int key;
el *next;
} *start;
void init();
void add(int n);
void list();
void search(int n); // ima za dopylvane
void deleter(int n);
void main() {
init();
int n, num;
do {
cout << "\n Menu\n";
cout << "\n1 - Add element";
cout << "\n2 - List elements";
cout << "\n3 - Searching for element";
cout << "\n4 - Delete element";
cout << "\n5 - Exit";
cout << "\n Your choice:";
cin >> n;
switch (n) {
case 1:
{
cout << "\n Input num:";
cin >> num;
add(num);
break;
}
case 2:
{
list();
break;
}
case 3:
{
cout << "\n Input num for searching:";
cin >> num;
search(num);
break;
}
case 4:
{
cout << "\n Input num for deleting:";
cin >> num;
deleter(num);
break;
}
}
}
while (n != 5);
}
void list() {
el *p = start;
if (start) while (p) {
cout << p->key << " ";
p = p->next;
} else cout << "\n Empty list";
}
void init() {
start = NULL;
}
void add(int n) {
el *p = start;
if (!start) {
start = new el;
start->key = n;
start->next = NULL;
} else {
if (start->key > n) {
start = new el;
start->key = n;
start->next = p;
} else {
el * q;
while ((p->key < n) && (p->next)) {
q = p;
p = p->next;
}
if (p->key > n) {
el *s;
s = new el;
s->key = n;
s->next = p;
q->next = s;
} else {
el *s;
s = new el;
s->key = n;
s->next = NULL;
p->next = s;
}
}
}
}
void search(int n) {
el *p = start;
if (!start) cout << "\nEmpty list!";
else while ((p->key != n) && (p-> next))
p = p->next;
if (p->key == n) cout << "\nYes!";
else cout << "\nNo!";
}
void deleter(int n) {
el *p = start;
if (!start) cout << "Enfsad";
else while ((p->key != n) && (p->next)) {
n = start->key;
start = start->next;
delete p;
}
}
Your deleter function should be like this.
void deleter (int n)
{
el *p = start;
el *prev = p;
if (!start)
{
cout<<"Enfsad";
}
if(start->key == n)
{
start = start->next;
delete prev;
}
else
{
while (p)
{
if(p->key == n)
{
prev->next = p->next;
p->next = NULL;
delete p;
break;
}
prev = p;
p = p->next;
}
}
}
Although I think you need to check how a good linked list should be.