How to swaps first and last element of a queue in C++? - c++

I have written a function to swap first and last elements of a queue in C++
void swap(queue Q)
{
queue temp;
createQ (temp);
int x,first,last;
first=dequeue(Q);
while(!isemptyQ(Q))
{
x=dequeue(Q);
last=x;
enqueue(x,temp);
}
enqueue(last,Q);
while(!isemptyQ(temp))
{
x=dequeue(temp);
if(x!=last) enqueue(x,Q); //(if) to avoid adding last element again
}
enqueue(first,Q)
}
note: "just consider (isempty,dequeue,createQ and enqueue) are other functions>>(my first year)"
but if the last element was duplicated in the middle like that
if that are the elements of the queue (5,1,9,3,9)
if we trace that function on these elements it would be (9,1,3,5)
there's a 9 missing !!
so if there's an escape from that or any other idea for the function ?!

No need to check for last if you don't push it.o I would rather do something like:
while(!isemptyQ(Q))
{
x=dequeue(Q);
if (isemptyQ(Q))
{
last=x;
}
else
{
enqueue(x,temp);
}
}
enqueue(last,Q);
while(!isemptyQ(temp))
{
x=dequeue(temp);
enqueue(x,Q);
}
By the way, your code won't work for empty or 1 element queues.

Below is pseudo code that tries to cover all special cases including 1 or zero elements in the queue
swap_first_last(q) {
dequeue(q, x, isEmpty);
initialize(tmp);
first = x;
count = 0;
while(!isEmpty) {
count ++;
last = x;
dequeue(q, x, isEmpty);
if(!isEmpty) {
enqueue(tmp, last);
}
}
if(count == 0) return;
enqueue(q, last);
if(count >= 2) {
dequeue(tmp, x, isEmpty);
while(!isEmpty) {
dequeue(tmp, x, isEmpty);
if(!isEmpty) {
enqueue(q, x);
}
}
enqueue(q, first);
}
}

Related

Sub array with a given sum

(The given problem is referred from : https://practice.geeksforgeeks.org/problems/subarray-with-given-sum-1587115621/1?page=1&difficulty[]=0&curated[]=1&sortBy=submissions )
I tried a solution to the above problem but it failed for large values for N and S.
I attempted the following solution to the above problem:
class Solution
{
public:
//Function to find a continuous sub-array which adds up to a given number.
vector<int> subarraySum(int arr[], int n, long long s)
{
// Your code here
long long sum=arr[0];
int first=0,last=0;
vector<int> v{-1,-1};
vector<int> a{-1};
if(arr[0]==s)
{
v[0]=1;
v[1]=1;
return v;
}
for(int i=0;first<n && last<n;i++){
if(sum>s){
if(first==last && (last+1<n)){
sum=sum-arr[first]+arr[first+1];
first++;
last++;
}
else{
if(first==last && last==n-1){
break;
}
if(first<last)
{ sum=sum-arr[first];
first++;
}
} else if(sum<s){
last++;
sum+=arr[last];
}
else if(sum==s){
v[0]=first+1;
v[1]=last+1;
return v;
}
}
return a;
}
};
In the code, 'first' and 'last' are the indexed of the first and the last element of the sub-array.
(Edit: The edited code works!, thanks for all the help!)

What is the error in this code,In 2d vector how the extra elements gets added?

How again -1,2,-1 gets included in the next pair?
The question is:
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<int>r1;
vector<vector<int>>resvec;
int s=nums.size();
int i=0,j,k=s-1;
for(;k-i>=2;k--)
{
for(j=i+1;j<k;j++)
{
if(nums[i]+nums[j]+nums[k]==0)
{
r1.push_back(nums[i]);
r1.push_back(nums[j]);
r1.push_back(nums[k]);
resvec.push_back(r1);
}
}
}
if(s>=3)
return resvec;
else
return {};
}
};
I was expecting this output:
[[-1,-1,2],[-1,0,1]]
Why it's giving output like this:
[[-1,2,-1],[-1,2,-1,-1,0,1]]
You forgot to clear r1 before adding new elemnets.
if(nums[i]+nums[j]+nums[k]==0)
{
r1.clear(); // clear the vector (erase the extra elements)
r1.push_back(nums[i]);
r1.push_back(nums[j]);
r1.push_back(nums[k]);
resvec.push_back(r1);
}
Instead of clearing, you should declare r1 inside the inner if:
if(nums[i]+nums[j]+nums[k]==0)
{
vector<int>r1; // declare here, not top of the function
r1.push_back(nums[i]);
r1.push_back(nums[j]);
r1.push_back(nums[k]);
resvec.push_back(r1);
}
Another way in C++11 or later is constructing the vector to add directly without extra variables:
if(nums[i]+nums[j]+nums[k]==0)
{
resvec.push_back(vector<int>{nums[i], nums[j], nums[k]});
}

Sorting linked list in C++ fails at runtime

void head_insert(DomesticPtr& head, string firstNameD, string lastNameD, string province, float cgpaD, int researchScoreD, int idD)
{
DomesticPtr temp_ptr;
DomesticPtr temp2;
temp_ptr= new DomesticStudent(head, firstNameD, lastNameD, province,cgpaD,researchScoreD,idD);
temp2 = head->getLink();
temp2==temp_ptr;
head=temp_ptr;
if (head->getLink() == NULL)
return;
else
{
bubblesort(head);
}
}
void bubblesort(DomesticStudent* head)
{
int rsd;
int cgpad;
int p;
DomesticPtr tempc, tempd, tempe;
tempd=head;
tempe= head->getLink();
{
while(tempd != NULL)
{
rsd=compareResearchScore(tempd, tempe);
if (rsd==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if
else if (rsd==0)
{
cgpad= compareCGPA(tempe,tempd);
if (cgpad==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (cgpad[k]>cgpad[k+1])
else if(cgpad==0)
{
p=compareProvince(tempd,tempe);
if(p==1)
{
tempc=head;
head->next=head;
head=tempc;
}// if (p[k]>p[k+1])
}//
}// else if cgpad[k]
}// else if rsd[k]
// }
// }
tempd = tempe;
}
int compareResearchScore(DomesticPtr RSA, DomesticPtr RSB)
{
if (RSB == NULL || RSA==NULL )
{
return 0;
}
if (RSA->researchScoreD==RSB->researchScoreD) //compares if is the same for domesetic students returns value for bubble sort
{
return 0;
}
if (RSA->researchScoreD > RSB->researchScoreD)
{
return 1;
}
if (RSA->researchScoreD< RSB->researchScoreD)
{
return -1;
}
}
I'm trying to to have my linked list sorted every time a new node is inserted. It compiles but every time I try to run the program it is stuck on the point that I am trying to print my list. I have a destructor but no copy constructor or assignment operator.
The head_insert calls the sort function and the sort function calls the compare function to receive an integer output so that it can make a swap. I want to compare research, the cgpa, and then province. Any input would be much appreciated, this is for a project so I wouldn't like any blocks of code but if you could point me in the right direction or multiple directions.

C++ Priority Queue, logical error, can't figure out

I'm implementing a simple priority queue in C++.
However when it runs, it prints out gibberish numbers.
Am I somehow trying to access invalid entries in the array in my code?
Below is the code.
Also, is my "remove" function somehow not doing its job? Conceptually, shall I be putting null into the first entry and return whatever was just erased?
Thanks.
[Priority.h]
#ifndef Priority_h
#define Priority_h
class Priority
{
public:
Priority(void);
Priority(int s);
~Priority(void);
void insert(long value);
long remove();
long peekMin();
bool isEmpty();
bool isFull();
int maxSize;
long queArray [5];
int nItems;
private:
};
#endif
[Priority.cpp]
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
#include "Priority.h"
using namespace std;
Priority::Priority(void)
{
}
Priority::Priority(int s)
{
nItems = 0;
}
Priority::~Priority(void)
{
}
void Priority::insert(long item)
{
int j;
if(nItems==0) // if no items,
{
queArray[0] = item; nItems++;
}// insert at 0
else // if items,
{
for(j=nItems-1; j=0; j--) // start at end,
{
if( item > queArray[j] ) // if new item larger,
queArray[j+1] = queArray[j]; // shift upward
else // if smaller,
break; // done shifting
} // end for
queArray[j+1] = item; // insert it
nItems++;
} // end else (nItems > 0)
}
long Priority::remove()
{
return queArray[0];
}
long Priority::peekMin()
{
return queArray[nItems-1];
}
bool Priority::isEmpty()
{
return (nItems==0);
}
bool Priority::isFull()
{
return (nItems == maxSize);
}
int main ()
{
Priority thePQ;
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);
while( !thePQ.isEmpty() )
{
long item = thePQ.remove();
cout << item << " "; // 10, 20, 30, 40, 50
} // end while
cout << "" << endl;
system("pause");
}
Here is one error:
for(j=nItems-1; j=0; j--) // start at end,
^ this is assignment, not comparison.
I am also not convinced that there isn't an off-by-one error in
queArray[j+1] = item; // insert it
Finally, your default constructor fails to initialize nItems.
There could be further errors, but I'll stop at this.
I agree with the other answers here, but I would add this:
Your "Remove" method isn't actually removing anything - it is just returning the first element - but it doesn't do anything to the array itself.
Edited to say that your insert method needs some work - it may or may not write over the end of the array, but it is certainly confusing as to what it is doing.
Try initializing your queue array in the constructor.

sort an array of objects based on property c++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c++ sort with structs
#include <iostream>
using namespace std;
class fish{
private:
int size;
int price;
public:
fish()
{
size=0;
price=0;
}
void set_price(int x)
{
price=x;
}
void set_size(int g)
{
size=g;
}
int get_size()
{
return size;
}
int get_price()
{
return price;
}
void display()
{
cout<<" Fish price is "<<price<<" Fish size is "<<size<<endl;
}
void sort(fish h[5])
{
for (int o=0;o<=5;o++)
{
fish temp;
temp.set_price(0);
if (h[o].get_price()>h[o+1].get_price())
{
temp.get_price()=h[o].get_price();
h[o].get_price()=h[o+1].get_price();
h[o+1].get_price()=temp.get_price();
}
}
}
};
void main()
{
fish a;
fish b[5];
a.set_size(500);
a.set_price(2);
a.display();
for (int i=0;i<=5;i++)
{
b[i].set_size(i*2);
b[i].set_price(i*100);
}
for (i=0;i<=5;i++)
b[i].display();
}
I want to to find out how I send array b, and sorting it. Also I was going to ask about the destructors and where I can put them into my code.
To swap fish around when you are sorting you should write this
fish tmp = h[o];
h[o] = h[o+1];
h[o+1] = tmp;
You are sorting based on the fish price, but it's the whole fish that should be sorted.
On your other question, there is no need for destructor in this code. Your fish class doesn't need to do any 'clean up' so it doesn't need a destructor.
if you're looking to sort your array by a given element the STL container should be just fine, if not i would use this method
template<class T>
void quickSort(T * elements, unsigned int first, unsigned int last)
{
if(first < last) //make sure params are in bounds
{
T t = elements[first]; //t is PIVOT
unsigned lastLow = first; //create last low item
unsigned i; //used for loop/swapping
for(i = first + 1; i <= last; i++) //run through entire bounds
if(elements[i] < t) //if elements is less than Low
{
<< " adding one onto lastLow...\n";
lastLow++; //move lastLow up one
swap(elements,lastLow, i); //swap lastlow and i
}
swap(elements,first, lastLow); //swap first and lastlow
if(lastLow != first) //if lastlow is not first element
quickSort(elements, first, lastLow - 1);
if(lastLow != last) //if lastlow is not last element
quickSort(elements, lastLow + 1, last);
}
}
this is a common quicksort function used to sort an array. Just replace the right variables to represent your data E.g. T * elements becomes Fish * stuff, T t = Elements[first] becomes double price = stuff[first] and so on.