cannot use private part [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I had an exam and they asked about queues. I am wonder how a reverse method can be written without using any private part of the header file given. So the method must be written by using only public part of the file. Also you cannot create a new Queue, or delete the queue existing already. You cannot use inheritance, interface etc. Also the method is required to work in O(N) time complexity. It is too much required and I could not find a solution for it.
Header file is :
#include <iostream>
using namespace std;
class Queue
{
public:
Queue(); // Class constructor
~Queue(); // Class destuctor
void ClearQueue(); // Remove all items from the queue
bool Enqueue(int newItem); // Enter an item in the queue
int Dequeue(); // Remove an item from the queue
bool isEmpty(); // Return true if queue is empty
private:
struct Node(){
Node *next;
int item;
};
Node *front;
Node *back;
};
//and the prototype of the method wanted :
bool reverse(){
}

You could write a recursive function. Add the following function to your class:
bool reverse() {
if (this->isEmpty())
return true;
int value = this->Dequeue();
this->reverse();
this->Enqueue(value);
return true;
}
If you don't want the function to be a method of the class Queue and you have a global Queue-object queue, you could also write a global function like this:
bool reverse() {
if (queue.isEmpty())
return true;
int value = queue.Dequeue();
queue.reverse();
queue.Enqueue(value);
return true;
}
If you don't have a global Queue-object, you will have to pass the queue as parameter, see:
bool reverse(Queue& queue) {
if (queue.isEmpty())
return true;
int value = queue.Dequeue();
queue.reverse(queue);
queue.Enqueue(value);
return true;
}

Related

Missing template arguments before 's' C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Well I am doing an assignment but not sure what my problem is
this is my assignment
Instructions You have two parts to this assignment. The parts are related, but different in their implementation. To better understand the assignment itself, it may be helpful to go back through the book, slides, notes, etc. and do implementations of the regular array-based and linked list-based Stack, along with the Stack ADT.
Part I
One widespread use of stacks is to provide the undo operation, familiar to us from many different applications. While support for undo can be implemented with an unbounded stack (one that keeps growing and growing as long as memory permits), many applications provide only limited support for such an undo history. In other words, the stack is fixed-capacity.
When such a stack is full, and push is invoked, rather than throwing an exception, a more typical approach is to accept the pushed element at the top, while removing the oldest element from the bottom of the stack to make room. This is known as “leaking.” Note that this does not mean that the ADT exposes a method to allow removal from the bottom directly. This is only performed when the stack becomes full.
For this part, you are to give an implementation of such a LeakyStack abstraction, using some array-based implementation.
Note that you must create a Leaky Stack interface, and then use the C++ : operator to implement that interface (using public inheritance) with your LeakyArrayStack implementation. See the Interface specified near the end of the assignment instructions.
Part II Repeat Part I, but use a singly linked list instead of an array for the actual data storage, and allow for a maximum capacity specified as a parameter to the constructor.
NOTES: • Both the array-based and linked-list based Leaky Stacks should use the same LeakyStackInterface, specified below. Remember – this is a LeakyStack ADT. It specifies what the LeakyStack does, not how. So, the interface should not be different in order to provide an implementation. • Use public inheritance in both Parts • You should write a SinglyLinkedList class first, before trying to do part II o Then, use containment (aggregation or composition, a has-a relationship) to implement the part II
I GOT TO USE THE INTERFACE IN THE PICTURE
this is my code
#include <iostream>
#ifndef LEAKYStacksINTERFACE
#define LEAKYStacksINTERFACE
#define cap 10
using namespace std;
template<typename ItemType>
class LeakyStacksInterface
{ public:
//returns whether Stacks is empty or not
virtual bool isEmpty() const = 0;
//adds a new entry to the top of the Stacks
//if the Stacks is full, the bottom item is removed
//or "leaked" first, and then the new item is set to the top
//---> If the Stacks was full when the push was attempted, return false
//---> If the Stacks was not full when the push was attempted, return true
virtual bool push(const ItemType& newEntry) = 0;
//remove the top item
//if the Stacks is empty, return false to indicate failure
virtual bool pop() = 0;
//return a copy of the top of the Stacks
virtual ItemType peek() const = 0;
//destroys the Stacks and frees up memory
//that was allocated
// virtual ~StacksInterface() {}
};
template<typename ItemType>
struct node
{
int data;
struct node *next;
};
template<typename ItemType>
class Stacks : public LeakyStacksInterface<ItemType>
{
struct node<ItemType> *top;
public:
int size;
ItemType *myArray;
Stacks()
{
top=NULL;
size = 0;
myArray = new ItemType[cap];
}
~Stacks() {
size = 0;
}
public:
// pure virtual function providing interface framework.
bool isEmpty() const {
return(size == 0);
}
bool push(const ItemType& newEntry) {
if(size == cap) {
for(int i = 0; i < size-1; i++) {
myArray[i] = myArray[i+1];
}
myArray[size-1] = newEntry;
return false;
}
}
ItemType peek() const {
return myArray[size-1];
}
void display()
{
cout<<"Stacks: [ ";
for(int i=size-1; i>=0; i--)
{
cout<<myArray[i]<<" ";
}
cout<<" ] "<<endl;
}
};
int main()
{
Stacks s;
int choice;
while(1)
{
cout<<"n-----------------------------------------------------------";
cout<<"nttSTACK USING LINKED LISTnn";
cout<<"1:PUSHn2:POPn3:DISPLAY STACKn4:EXIT";
cout<<"nEnter your choice(1-4): ";
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
return 0;
break;
default:
cout<<"Please enter correct choice(1-4)!!";
break;
}
}
return 0;
}
#endif
HERE ARE MY ERRORS :
ERROR:missing template arguments before 's'
ERROR:expected ';' before 's'
ERROR:'s' was not delcared in this scope
please help!
Thank You!
INTERFACE PICTURE
Stacks is a class template, so to use it you must provide a template argument, like
Stacks<int> s;

My linked lists program terminated with status -1073741819 In Code blocks compiler(x0000000005)) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is the Program
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
node *next;
};
typedef node *list;
bool create(list header){
return header==NULL;
}
void insert_begining(list header,int item){
node*p;
p=new(node);
if (p=NULL)
{
return;
}
p->data=item;
p->next=header;
header=p;
}
void insert_end(list header,int item){
list p,q;
p=new(node);
p->data=item;
p->next=NULL;
if (header==NULL)
{
header=p;
}
else
{
q=header;
while(q->next!=NULL){
q=q->next;
}
q->next=p;
}
}
void print_list(list header){
node* p;
p=header;
while(p->next!=NULL){
cout<<p->data<<endl;
p=p->next;
}
}
int main(){
list header;
create(header);
insert_end(header,500);
insert_end(header,600);
insert_end(header,4);
insert_end(header,6);
print_list(header);
return 0;
}
i run the program and it shows
Process returned -1073741819 (0xC0000005) execution time : 6.720 s
i really don't know why.I think that the syntax is right
pleases check the program above and tell me what to do.
i am a beginner and i really don't know much about linked lists
First, you need to understand pass-by-value vs pass-by-reference. In the former case a copy of the var is passed and in the latter the actual var is passed. Ex:
void f1(int x) { // Pass by value
x = 1;
}
void f2(int& x) { // Pass by reference
x = 2;
}
int main() {
int y = 0;
f1(y);
// y is still 0
f2(y);
// y is now 2
}
In your program, you pass header by value:
void insert_begining(list header,int item){
// ....
header=p; // Only modifying the local var!
}
Some things I would do:
First, get rid of that typedef. This is C++ but you are not using classes, so I assume you haven't learned them yet. Instead, create a linked list struct:
struct node
{
int data;
node *next;
};
struct linked_list {
struct node *head;
linked_list() : head(nullptr) {} // ctor
};
No more typedef needed, and now you can easily pass by reference. Ex:
void insert_begining(linked_list& list, int item){
// removed for brevity
p->next = list.head;
list.head = p;
}
When you declare the header variable it is not initialized to NULL. In C++
variables are usually not initialized by the compiler upon declaration.
So when you make the call
insert_end(header, 500);
inside the function the else block is executed since header is not NULL but a garbage value. The culprit here is:
while(q->next!=NULL);
You cannot evaluate q->next since q points to a random memory location and hence the segfault. You need to assign to a variable before accessing it.
So in you main function add this:
list header = NULL;
Apart for this your might want to check BLUPIX's comments about other problems.
Also use nullptr instead of NULL if the compiler supports C++11

Why did my C++mprogram stop working after being compiled? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm a computer science student and have been coding with Java for the past year. Now I'm interested in learning C++. The first program that I wanted to code with C++ is an implementation of stack using linked list, which I have coded before using java. I pretty much have no idea what I'm doing and basically just writing what I thought was right until I got no compile error. So I finally did it, my program got no compile error, but when I ran it, a pop-up appeared saying that my 'Stack.exe has stopped working'
Here's my code:`
#include <iostream>
using namespace std;
class Stack;
class Node;
class Node
{
public:
string element;
Node *next;
Node(string, Node);
};
Node::Node(string element, Node next)
{
this -> element = element;
*(this -> next) = next;
}
class Stack
{
private:
Node *tos;
public:
Stack()
{
tos = NULL;
}
void push(string str)
{
tos = new Node(str, *tos);
}
string peek()
{
return tos->element;
}
string pop()
{
string temp = tos->element;
tos = (tos->next);
return temp;
}
};
int main(void)
{
Stack bob;
bob.push("Wow");
bob.push("Wiw");
cout << bob.peek();
return 0;
}
Can someone tell me what I did wrong? I did it like this because this was how I did it with Java.
Thank you :D
You're dereferencing null or undefined pointers in a couple places. First let's look at your Node constructor:
*(this -> next) = next;
Since next hasn't been defined yet, dereferencing it leads to undefined behavior. In practice, next will point to some random place in memory that you probably don't own, so writing to it will cause a program crash. Your Node constructor should take a pointer to Node as its second parameter instead of taking a Node by value:
Node::Node(string element, Node* next)
: element{element},
next{next}
{}
Note that I've also initialized Node's members instead of default-initializing them and then assigning to them in the constructor's body.
After fixing Node's constructor, you'll also need to fix Stack::push to pass a pointer instead of an object:
void push(string str)
{
tos = new Node(str, tos);
}
Note that even after fixing the crashing problem, you'll still leak memory when you pop from your Stack (or when a Stack is destroyed). You need to delete anything you new, or better yet use std::shared_ptr<Node> instead of raw Node*s.

Using Linked-lists to implement a stack, debug assertion failed

I am currently working on implementing a stack data structure using linked lists in C++. I can compile everything fine up until the point I test my "stack.push" method when I receive a debug assertion failed error that I have no where near enough knowledge as to how to begin to fix it. I just started on here so I cannot post images apparently, but in short it says:
Debug Assertion Failed!
Program...ual studio 2013/....~
File:f:/dd/vctools/crt/crtw32/misc/dbgdel.cpp
Line: 52
Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse
and here are my codes: Stack.h
#ifndef _STACK_H
#define _STACK_H
#include "LList.h"
typedef int ItemType;
class Stack{
public:
Stack();
~Stack();
int size() { return size_; }
void push(ItemType x);
ItemType pop();
ItemType top() { return top_; }
private:
ItemType top_;
void copy(const Stack &source);
int size_;
LList items_;
};
#endif _STACK_H
stack.cpp:
#include "Stack.h"
Stack::Stack()
{
size_ = 0;
ItemType top_ = NULL;
}
void Stack::push(ItemType x)
{
items_.append(x);
size_ += 1;
ItemType top_ = x;
}
ItemType Stack::pop()
{
ItemType top_ = size_ - 1;
size_ -= 1;
return items_.pop();
}
Stack::~Stack()
{
items_.~items_();
}
The error occurs after writing test code that assigns a stack and then tries to push a number onto the stack.
Any help would be appreciated and I apologize if there are any formatting issues with my post.
There are several problems with your code:
Like mentioned in another answer, append will add the item at the end of the list (i.e., at the bottom from stack perspective) instead of at the top.
Your usage of top is inconsistent, you should decide what it means. Classically, top would hold or point to the last inserted element.
You have syntax issues and you're actually redeclaring a new local variable for top instead of using the class member.
You have memory corruption in the destructor when you explicitly call the contained list destructor.
You are a bit confused as to what append does. Append places a value (in this case an ItemType x) to the end of your stack, not the front. You then assign the top of the stack to the end of the stack, and you lose the pointers to the head of your list.
In fact, there are multiple things wrong now that I look at the rest of your code. I think you lack an understanding of what Linked Lists do, and you should go and read them yourself instead of me just dropping working code in my answer.

[c++]The importance of dynamic allocation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I wrote a doubly linked list, and trying to add an append()(insert at the end)and len()(caculate the number of member in the list). I just don't understand why it doesn't work now. Here is the simplest code:
#include<iostream>
using namespace std;
class linkedList{
private:
struct node{
node* last;
node* next;
char* str;
};
node sentinel;
public:
linkedList();
~linkedList();
int len();
void append(char*);
};
linkedList::linkedList(){
sentinel.last=&sentinel;
sentinel.next=&sentinel;
sentinel.str="I am sentinel!!";
};
linkedList::~linkedList(){};
int linkedList::len(){
node* currentNode=&sentinel;
int count=0;
while ((*currentNode).next!=&sentinel){
count++;
currentNode=(*currentNode).next;
cout<<(*currentNode).str<<endl;
}
return count;
}
void linkedList::append(char* str){
node newNode;
newNode.str=str;
newNode.last=sentinel.last;
(*sentinel.last).next=&newNode;
sentinel.last=&newNode;
newNode.next=&sentinel;
}
int main(){
linkedList myList;
myList.append("Hello");
myList.append("World");
int length=myList.len();
cout<<length<<endl;
return 0;
}
What I am doing is just add two new nodes into the linked list, and caculate the total number of my nodes. it should return 2. but why it doesn't work?
newNode in your code below will go out of scope as soon as append is finished executing. Assigning it's memory address as a pointer to more global member is likely going to end in a segfault.
void linkedList::append(char* str){
node newNode;
newNode.str=str;
newNode.last=sentinel.last;
(*sentinel.last).next=&newNode;
sentinel.last=&newNode;
newNode.next=&sentinel;
}
Try allocating your node on the heap using new node, possibly using a shared_ptr to make memory management a bit simpler.
void linkedList::append(char* str){
node *newNode = new node;
newNode->str=str;
newNode->last=sentinel.last;
(*sentinel.last).next=newNode;
sentinel.last=newNode;
newNode->next=&sentinel;
}
With this approach, be sure to cleanup the nodes when destructing your linkedlist, via the delete operator on each node.
Alternatively, look into using shared_ptr's to a Node instead of raw pointers, which will always call delete when the linkedlist (and nobody else) is pointing to the node.
Use the new keyword to allocate a new node:
void linkedList::append(char* str){
node *newNode = new node();
newNode->str=str;
newNode->last=sentinel.last;
(*sentinel.last).next=newNode;
sentinel.last=newNode;
newNode->next=&sentinel;
}