Inserting linked list in C++ - c++

I need to insert 0 between two negative values in linked list. But my function doesn't work. What's wrong?
P. S. listLength passes information about length of linked list.
Insert function:
void insert(int new_value, int preceed_num)
{
struct List1* last;
struct List1 *brand_new;
brand_new = new(struct List1);
last = getAddress(preceed_num - 1);
brand_new -> Next = last -> Next;
last -> Next = brand_new;
brand_new -> Info = new_value;
amount++;
}
Inserting zero between two values function:
void insert_zero_unction()
{
int length = listLength();
int first, second;
for(int count = 1; count < length; count++)
{
first = getValue(count);
second = getValue(count + 1);
if(first < 0 && second < 0)
{
insert(0, first);
length++;
}
}
}

as #molbdnilo and #user4581301 said, traversing the list and using pointers in algorithm solved the problem. Here is re-written code:
void Zeroed_Stack_Function()
{
int length = listLength();
struct List1* first, *second;
int count = 1;
int to_past;
while(count <= length)
{
first = getAddress(count - 1);
second = getAddress(count);
if(first -> Info < 0 && second -> Info < 0)
{
insert(0, count);
}
length = listLength();
count++;
}
}

Related

Trying to print out the elements in the last level of a min heap

I'm trying to print the last level in a min heap. I thought I had code that works, but one of the test cases fail. In terms of the test cases, I only have access to how the output does not match.
Here is my code:
#include "MinHeap.h"
#include <math.h>
using std::log2;
vector<int> lastLevel(MinHeap & heap)
{
// Your code here
vector<int> leaves;
int capacity = pow(2, log2(heap.elements.size()) + 1) - 1;
for (unsigned leaf = capacity / 2; leaf < heap.elements.size(); leaf++) {
leaves.push_back(heap.elements[leaf]);
}
return leaves;
}
And here is the MinHeap class that goes along with it:
#include "MinHeap.h"
MinHeap::MinHeap(const vector<int> & vector)
{
int inf = numeric_limits<int>::min();
elements.push_back(inf);
elements.insert(elements.end(), vector.begin(), vector.end());
buildHeap();
}
MinHeap::MinHeap()
{
int inf = numeric_limits<int>::min();
elements.push_back(inf);
}
void MinHeap::buildHeap()
{
std::sort(elements.begin() + 1, elements.end());
}
void MinHeap::heapifyDown(int index)
{
int length = elements.size();
int leftChildIndex = 2 * index;
int rightChildIndex = 2 * index + 1;
if (leftChildIndex >= length)
return; // index is a leaf
int minIndex = index;
if (elements[index] > elements[leftChildIndex]) {
minIndex = leftChildIndex;
}
if ((rightChildIndex < length)
&& (elements[minIndex] > elements[rightChildIndex])) {
minIndex = rightChildIndex;
}
if (minIndex != index) {
// need to swap
int temp = elements[index];
elements[index] = elements[minIndex];
elements[minIndex] = temp;
heapifyDown(minIndex);
}
}
void MinHeap::heapifyUp(int index)
{
if (index < 2)
return;
int parentIndex = index / 2;
if (elements[parentIndex] > elements[index]) {
int temp = elements[parentIndex];
elements[parentIndex] = elements[index];
elements[index] = temp;
heapifyUp(parentIndex);
}
}
void MinHeap::insert(int newValue)
{
int length = elements.size();
elements.push_back(newValue);
heapifyUp(length);
}
int MinHeap::peek() const
{
return elements.at(1);
}
int MinHeap::pop()
{
int length = elements.size();
int p = -1;
if (length > 1) {
p = elements[1];
elements[1] = elements[length - 1];
elements.pop_back();
heapifyDown(1);
}
return p;
}
void MinHeap::print() const
{
if (elements.size() > 1) {
int length = elements.size();
cout << "[";
for (int i = 1; i < length - 1; i++) {
cout << elements[i] << ", ";
}
cout << elements[elements.size() - 1] << "]" << endl;
} else {
cout << "[ ]" << endl;
}
}
Here is the output I get showing one of the test cases fail:
tests.cpp:31: FAILED:
REQUIRE( s_lastLevel(h) == lastLevel(h) )
with expansion:
{ 1804289383 (0x6b8b4567), 1681692777 (0x643c9869) }
==
{ 1681692777 (0x643c9869) }
===============================================================================
test cases: 1 | 1 failed
assertions: 3 | 2 passed | 1 failed
I'm not sure why my initial approach is failing. Much help is appreciated.
It seems like the problem is in this line:
int capacity = pow(2, log2(heap.elements.size()) + 1) - 1;
What you are doing here is equivalent to:
int capacity = 2 * heap.elements.size() - 1;
What you instead want to do is get the index of the parent of the last element and increment by one as the starting position of your iteration. Since children of a node at i are at 2i and 2i+1, you can simply divide the index of the last node (n-1) by two and add one. You can check that this must be a leaf since its children would be at 2 * ((n-1)/2 + 1) and 2 * ((n-1)/2 + 1) + 1 which are both guaranteed equal or grater than n. So this will return all leaves:
int start = (heap.elements.size() - 1) / 2 + 1;
for (unsigned leaf = start; leaf < heap.elements.size(); leaf++) {
leaves.push_back(heap.elements[leaf]);
}
return leaves;
If it is just the last level you want, start at the largest power of two smaller than the index of the last element (n-1):
int start = 1 << (int)(log2(heap.elements.size()-1));
for (unsigned leaf = start; leaf < heap.elements.size(); leaf++) {
leaves.push_back(heap.elements[leaf]);
}
return leaves;

Code giving Run Time Error for the problem Maximum XOR pair in a given Range

I am trying to solve a well known problem called the Maximum XOR pair ina given range. If you are unaware about the probelm here is the prompt given to me:
You are given an array and Q queries of two types.
Type 0: Given a number x , insert the number at the last of the array.
Type 1: Given a number X and two integers L, R, Find a number Y in the range L, R to maximize X ^ Y
Input Format
First line of the test case will be the number of queries Q . Then on next Q subsequent lines you will be given a query either of type 0 or type 1. Query of type 0 is of the form : 0 X, where X is the integer to be inserted . Query of type 1 is of the form : 1 L R X
Constraints
0 <= element of array <= 10^9
1 <= N <= 10^5
Output Format
For each query of type 1 output the desired value.
Sample Input
5
0 3
0 5
0 10
0 6
1 1 4 6
Sample Output
10
I am using Tries to find out the maximum XOR for the given question my for some reason it gives a Run Time Error in 2 test cases. I am not sure why is that. Please help!
Here is my code:
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int index;
node * left; // data = 0
node * right; // data = 1
};
class Trie {
node * root;
public:
Trie() {
root = new node();
}
void insert(int n, int idx) {
// ith bit of a number is (n >> i) & 1
node * temp = root;
for(int i = 31; i >= 0; i--) {
int bit = (n >> i) & 1;
if(bit == 0) {
if(temp->left == NULL) {
temp->left = new node();
temp->index = idx;
}
temp = temp->left;
}
else {
if(temp->right == NULL) {
temp->right = new node();
temp->index = idx;
}
temp = temp->right;
}
}
}
int max_xor_helper(long long int value, int L, int R) {
node * temp = root;
long long int current_ans = 0;
for(int j = 31; j >= 0; j--) {
int bit = (value >> j) & 1;
if(bit == 0) {
// finding complimentary value
if(temp->right != NULL and temp->index >= L and temp->index <= R) {
temp = temp->right;
current_ans += (1 << j); // 2 ^ j
}
else {
temp = temp->left;
}
}
else {
if(temp->left != NULL and temp->index >= L and temp->index <= R) {
temp = temp->left;
}
else {
temp = temp->right;
current_ans += (1 << j);
}
}
}
return current_ans;
}
};
int maxXORPair(Trie root, int L, int R, int X) {
// Trie root;
// int max_xor = 0, max_xor_partner = 0;
// for(int i = L; i <= R; i++) {
// int val = arr[i];
// root.insert(val);
// int curr_ans = root.max_xor_helper(X, L, R);
// if(curr_ans > max_xor) {
// max_xor_partner = curr_ans ^ val;
// max_xor = curr_ans;
// }
// }
return root.max_xor_helper(X, L, R);
}
int main() {
Trie root;
int idx = 0;
// vector<int> v;
int queries;
cin>>queries;
for(int i = 0; i < queries; i++) {
int type;
cin>>type;
if(type == 0) {
long long int val;
cin>>val;
root.insert(val, idx);
idx++;
// v.push_back(val);
}
else {
int L, R;
cin>>L>>R;
long long int X;
cin>>X;
long int ans = maxXORPair(root, L, R, X);
cout<<ans<<endl;
}
}
return 0;
}
See: https://www.learncpp.com/cpp-tutorial/null-pointers
Just like normal variables, pointers are not initialized when they are instantiated.
Initialize your pointers to NULL.

Josephus Election Problem array implementation

I am trying to implement the Josephus election problem using an array as a mock circular linkedlist.
The item and next arrays represent nodes for circular linked list. On every Mth element one element is marked for removal. The next array skips over the marked index.
When there is one element left in the array we print out the element and the item that is left.
The problem is from Sedgewick C++ Algorithms books Chapter Third Edition. exercise 3.31.
The output I am getting is incorrect, I am not lost.
void array_represent_linked_list(int num_ints, int M) {
int* item = new int[num_ints];
int* next = new int[num_ints];
//populated item and next array with elements
for (int index = 0; index < num_ints; index++) {
item[index] = index + 1;
if (index == (num_ints - 1)) {
next[index] = 0;
}
else {
next[index] = index + 1;
}
}
int nums_left = num_ints;
int x = 0;
int count = 0;
int last_element_index = 0;
while ( nums_left > 1) {
//if current value divisible by M-2?
if ((count % M-2) == 0) {
if ((nums_left - 1) == 1) {
//record the next index which is the last element
last_element_index = next[x];
}
else {
//mark for removal of element from array
next[x] = next[next[x]];
}
nums_left -= 1;
}
//move to next element of array
x = next[x];
count++;
}
std::cout << item[last_element_index]<< " " << last_element_index<< std::endl;
}
output for
array_represent_linked_list(9,5); //item[x] =8 , next[x] = 7
After writing a brute force method which looks at each individual element in the item array and setting each element to 0 when we reach a skip factor of M. I was able to test with this code snippet and get the correct answers.
Breaking down the problem, every M-1 elements should set the next[index] to next[next[index]] , and we traverse the array with x = next[x].
void array_represent_linked_list(int num_ints, int M) {
int* item = new int[num_ints];
int* next = new int[num_ints];
//populated item and next array with elements
for (int index = 0; index < num_ints; index++) {
item[index] = index + 1;
if (index == (num_ints - 1)) {
next[index] = 0;
}
else {
next[index] = index + 1;
}
}
int nums_left = num_ints;
//used to track elements in item array
int index = 0;
//used to count number of elemenets traversed in the list
int count = 0;
//store the return values
int return_index = 0;
int return_val = 0;
while (nums_left > 1) {
count += 1;
if (count == (M - 1)) {
//reset the count after reaching 4 elements
count = 0;
//update next element
next[index] = next[next[index]];
//decrease nums found
nums_left -= 1;
}
//traverse to next element
index = next[index];
}
return_index = index;
return_val = item[next[index]];
std::cout << return_index << " " << return_val << std::endl;
}
The book gives a linked list implementation similar to the following:
struct node {
int item;
node* next;
node(int x, node* t) {
item = x;
next = t;
}
};
typedef node *link;
int josephusLinkedList(int n, int k) {
link t = new node(1, 0);
t->next = t;
link x = t;
for (int i = 2; i <= n; i++) {
x = (x->next = new node(i, t));
}
while (x != x->next) {
for (int i = 1; i < k; i++) x = x->next;
x->next = x->next->next;
}
return x->item;
}
We can write a very similar implementation that simulates the linked list using an array next where the index of the array represents the node and the value represents the pointer to the next node.
int josephusArray(int n, int k) {
int *next = new int[n];
for (int i = 0; i < n; i++) {
next[i] = (i + 1) % n;
}
int x = 0;
while (x != next[x]) {
for (int j = 1; j < k; j++) x = next[x];
next[x] = next[next[x]];
}
return x;
}
We initialize the next array by setting each value to the next index, until we reach the end, which we set to 0, the first index. This simulates the circular linked list that is the starting condition of the problem.
The while loop then eliminates every kth element by advancing through the next array k-1 times, then "removing" the next element by setting next[x] = next[next[x]];, which is very similar to how we remove an element from a linked list. (The element isn't really removed from the array, but it will be skipped in future traversals because no value will point to that element.)

Using a insertion sort function for two dimensional array in C++?

One of the functions I am doing uses a insertion sort for a two dimensional array with 2 rows and 12 columns. The first row is for student IDs, so there are 12 students total. The second row has the corresponding GPA for each student. I am not sure how to come up with an insertion sort to sort the GPA numbers in ascending order. Any help would be awesome!
I have this so far.
void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
int temp;
int walker;
int row = 1;
while (current <= last)
{
temp = avg[row][current];
walker = current - 1;
while (walker >= 0
&& temp < avg[row][walker])
{
avg[row][walker+1] = avg[row][walker];
walker = walker - 1;
}
avg[row][walker+1] = temp;
current = current + 1;
}
Your problem is that temp variable is declared as an int it should be double also you should swap the ids too
void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
double temp;//this was an int
int walker;
int row = 1;
while (current <= last)
{
temp = avg[row][current];
walker = current - 1;
while (walker >= 0
&& temp < avg[row][walker])
{
avg[row][walker+1] = avg[row][walker];
avg[row-1][walker+1] = avg[row-1][walker];//swap the id of two students
walker = walker - 1;
}
avg[row][walker+1] = temp;
avg[row-1][walker+1] = temp;
current = current + 1;
}
}

Bubble Sort Ragged Table in C

I was trying to sort a ragged table using bubble sort. The algorithm I have only sorts the first row, but leaves the rest of the rows unsorted. I think the problem is the fact that the "last" variable is not properly initialized.
void bubbleSort (int **table)
{
// Local Declarations
int temp;
int current;
int walker;
int column;
int row=0;
int numCol = 0;
int last = *table[numCol];
// Statements
while (table[row] != NULL) {
for (column = 2; column <= *table[row]; column++) {
for (current = 2; current < last; current++) {
bool swapsOccured = false;
for (walker = last; walker > current; walker--) {
if (table[row][walker] > table[row][walker - 1]) {
swapsOccured = true;
temp = table[row][walker];
table[row][walker] = table[row][walker - 1];
table[row][walker - 1] = temp;
} // if
} // for walker
if (!swapsOccured)
return;
} // for current
}
row++;
} // while
return;
}