Finding last element in linked structure heap - c++

I was wondering how you would go about finding the furthest element in a linked structure implementation of a heap and the root element. I want to be able to Enque and Deque elements.
Some clarification:
what I meant was lets say you have a linked structure making up a max heap (root element has the largest value). Your tree would have an element somewhere at the very bottom which you would insert after or remove depending on if you are enqueing or dequeing. How do you determine that element? and how do you determine the root node of the tree? (the top one)

I'm not completely positive this is what you are asking for, but this is one way of pointing to the last element of a singly-linked list:
T *p = NULL, *q = NULL; // q follows p by one node
p = root;
while (p)
{
q = p;
p = p -> next;
}
// q now points to last node

The normal method for adding something to a heap structure is to start at the root and "walk" the tree to find the place where the new element goes. When you find where it goes, you put it there, and if that means replacing what's already in that spot, then you take the previous value and keep walking down to find where it goes. Repeat until you hit a leaf, then add whatever value you're "carrying" as the appropriate child of that leaf.
Suppose your new value was 5 and the root node of the heap held a 10. 5 clearly goes below 10, so you look at the children of 10. Suppose they're 8 and 7. Both are larger than 5, so pick one (how you pick one depends on whether you're trying to keep the heap balanced). Suppose you pick 7, and it has children 3 and 4. 5 goes below 7 but above 3 or 4, so you replace, say, the 4 with 5, then look at that node's children to see where to put the 4. Suppose it has no children, you can just add a new leaf containing 4.
As for your question about how you find the root -- generally the root is the only pointer to the tree that you keep. It's your starting point for all operations. If you started somewhere else, I suppose you could navigate up to the root, but I'd question why.

Maybe something like this ?
struct node {
node *parent;
node *children[2];
int data; //or whatever else you want
};
struct heap {
node *root;
node *last;
};
This is a lot trickier to implement then just using an array though. Here is a hypothetical add
void add(struct heap* h, int d)
{
node* add = malloc(sizeof(node));
add->data = d;
node* current = h->root;
while(current->children[1]) current = current->children[1];
current->children[1] = add;
add.parent = current;
add.children[0] = NULL;
add.children[1] = NULL;
h.last = add;
percolate_up(h);
}
Something like that.

Related

Pairwise swapping of elements in a linked list (by changing pointers)

The problem statement is the following:
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5
Here is my solution:
void swapPairs(Node* head) {
if (!head->next || !head)return head;
Node* current = head->next;
Node*prev = head;
while (true) {
Node* next = current->next;
current->next = prev;
if (!next || !next->next) {
prev->next = next;
break;
}
prev->next = next->next;
prev = next;
current = prev->next;
}
}
The issue with the solution is that when it gets to the end of the function, the head no longer points to the beginning of the list since both current and prev have been moved. I've seen other solutions online which do the same thing as I'm doing here, but maybe since they are implemented in C instead of C++, there is some aspect of their code that allows for the head to remain pointing to the start of the list.
I realize that this is probably a really simple issue to solve, but I'm just not currently seeing the solution. What would be the best way to maintain the beginning of the list throughout the algorithm?
The task at hand will be much simpler once you undergo a slight paradigm shift. This might seem more complicated at first, but after pondering it a bit, its simplicity should be obvious.
Simply said: instead of carrying a pointer around -- to the first of each pair of list elements -- as you walk through the list, carry a pointer to the pointer to the first of each pair of list elements. This sounds complicated, on its face value; but once the dust settles, this simplifies the task at hand greatly.
You must have a head pointer stored separately, and you're passing it to swapPairs():
Node *head;
// The list gets populated here, then ...
swapPairs(head);
That's what you're doing now. But rather than doing this, pass a pointer to the head node, instead:
swapPairs(&head);
// ...
void swapPairs(Node **ptr)
{
while ( (*ptr) && (*ptr)->next)
{
// swap the next two elements in the list
// ...
// Now, advance by two elements, after swapping them.
ptr= &(*ptr)->next->next;
}
}
The body of the while loop is going to swap the next two elements in the list, and let's skip over that part for now, and just focus on this bit of logic that iterates through this linked list, a pair of elements at a time. What's going on here?
Well, you are trying to walk through the list, two elements at a time.
Remember, ptr is no longer the pointer to the first element of the pair. It's a pointer to wherever the pointer to the first element of the pair happens to live. So the initial ptr is pointing to your original head pointer.
Once you understand that, the next mental leap is to understand that you want to cycle through your iteration as long as there are at least two elements left in the list:
while ( (*ptr) && (*ptr)->next)
*ptr is the next element to the list, the first of the pair, and (*ptr)->next would therefore be the pointer to the second in the pair. Because of how we're iterating, ptr can be proven, by contract to never be NULL. So, if *ptr is NULL, you reached the end of the list. But if *ptr is not NULL, there's at least one element left, and (*ptr)->next is the "next 2nd element". If (*ptr)->next is NULL, the original list had an odd number of elements in it, so on the last iteration you ended up with *ptr pointing to the odd duck. And you're done in that case too, no need to go any further.
Finally:
ptr= &(*ptr)->next->next;
This simply advances ptr by two elements of the list. Remember, ptr is a pointer to wherever the pointer to the first of the next two elements in the list "happens to live", and this now sets ptr to point the where the pointer to the first of the ***next**** two elements in the list happens to live. Take a piece of paper, draw some diagrams, and figure this out yourself. Do not pass "Go", do not collect $200, until this sinks in.
Once you wrapped your brain around that, the only thing that's left is to swap the pairs. That's it. The body of the loop can simply be:
Node *first=*ptr;
Node *second=first->next;
Node *next=second->next;
*ptr=second;
second->next=first;
first->next=next;
That's it. You're done. And, guess what? Your original head is now automatically pointing to the right head node of the swapped list.
Now, wasn't that easy?
Change the signature of the function to
Node* swapPairs(Node* head)
and save the new head after the first swap, then at the end after your while loop's closing }, return that new head, to replace the old list head held by the caller, which would use this something like:
list = swapPairs(list);
You can keep a pointer to the new head at the beginning of the function and update the head at the end of the function with that. Note that I changed the argument from Node* to Node ** because we want to update the pointer value so that when we update head, we write to the same memory location that passed to this function. As a result, the correct value of head will be available in the caller of this function when we return from it.
void swapPairs(Node **head) {
if (!(*head)->next || !(*head))
return;
Node *new_head = (*head)->next; // the new_head
Node *current = (*head)->next;
Node *prev = (*head);
while (true) {
Node *next = current->next;
current->next = prev;
if (!next || !next->next) {
prev->next = next;
break;
}
prev->next = next->next;
prev = next;
current = prev->next;
}
*head = new_head; // now update the head
}

Is the root node of a singly linked list considered a part of the list?

A singly-linked list in C++, as I know it, is structured such that there is a root node which holds no values but the first element in a list of nodes. The nodes which are in the linked list headed by the root node (all of which hold data, and a pointer to the next node in the list).
A simple list skeleton (with no mutators or accessors) may look something like this:
class List {
private:
struct Node {
int value;
Node* next;
};
Node* root;
public:
List() {
root = new Node;
root->next = nullptr;
root->val = 0;
}
}
I would assume this all would mean that root->next would point to the first element in the list (meaning the root node is not the first element) correct?
A head node that isn't considered a regular node, can simplify (1)some list operations.
When there is one, it isn't considered part of the set of regular nodes, and if the list is abstracted, the head node is then usually not visible to client code.
Likewise one can have a tail node, but instead it's simpler to just use a circular list.
All that said, consider just using std::list where you need to insert or delete data without invalidating pointers to existing items.
And more in general, just use std::vector (except possibly for vector<bool>, where one might instead consider e.g. deque<bool>).
(1) E.g. deleting the first node that satisfies some criterion.

Just trying to insert a node and set the pointer in it to the next node C++

I feel really silly asking this, as it seems really simple, but I just can't figure it out. All I want to do is set the node pointer to the next node in the list. The function is from a teacher, I wrote the body, so I don't want to mess with the head of the function.
void LList::insert(int num, int at)
{
node* n = new node(num);
if (!n) throw runtime_error("Can't allocate node!");
if(!root || at == 0){
// if empty list - new node is root…
if (!root) root = n;
}
if(root){
node* nextNode = new node(num);
int numF = 0;
for (node* t = root; t != NULL ; t = t->next){
numF++;
if(numF == at){
n->next=t->next;
t->next=n;
}
}
}
}
Since it seems you are using n for the new node to be inserted into the linked list (I'm inferring that it's a singly linked list from the existing code and class name), there are a few things you have to do off the top of my head:
Identify the existing member of the list after which the new node will be inserted. You are making an attempt to do this already with that for loop, but in my opinion you may want to rewrite that as a while loop since you probably don't want it to keep iterating after the insertion position has been identified. Alternately, you could short-circuit out of the for loop with a break once you've found the right place for insertion, but I don't like that for stylistic reasons. :)
Set the newly inserted node's next pointer to the same location to which the next pointer of the node identified in #1.
Set the next pointer of the node identified in #1 to point at the new node, thus re-establishing the integrity of the chain.
Your code looks like it is attempting to do #2 and #3 out of order, which won't work. You're obliterating the value of t->next before you've had a chance to point n->next at it.
Finally, you may need to define some behavior to which you can fall back in case you are adding to a position not already defined in the list (i.e. inserting into the fourth position of a linked list that currently has three elements). You may need to re-jigger your loop to terminate when t->next is null rather than when t itself is null - otherwise you lose the hook to be able to connect the (currently) last element of the list to your new node.

Accessing Vector of Nodes

Just a quick C++ question. I've been trying to save a node inside a vector to the right child of a node.
For example,
I have a struct called node that has a pointer leading to a left child and a right child.
So:
struct node{
node *left;
node *right;
};
My vector of nodes,
vector<node> nodeVec;
consists of nodes as well.
The goal is to then take a node out of my vector and save as the right and left child of a new node.
So:
node *tree = new node();
tree->left = *nodeVec.at(0);
tree->right = *nodeVec.at(1);
But it throws an error saying that it doesn't recognize the '*' operator. Trying just
tree->left = nodeVec.at(0)
It says that I can't convert a node to a node*.
But if I use,
tree->left = &nodeVec.at(0)
It succesfully saves the address inside my left child.
I took a look at a couple of sites and answers and I think the one found here,
Dereference vector pointer to access element,
might've been the most relevant. I gave it a shot and threw so many errors, I didn't quite understand.
In short, from what i've read, I need to dereference the node inside my vector. But if it doesn't accept the '*' operator, how would one do that?
Thanks in advance!
You can access nodes in the vector like this:
node* p_left = nodeDev.at(0).left;
node copy_constructed_node(*(nodeDev.at(0).right));
You can also use your tree:
node* p_left = tree->left; // your code set this to &nodeVec[0]
More generally, I suggest you do some background reading on pointers (maybe here), or - better yet - consider whether a Standard container will satisfy your needs - e.g. std::map (tutorial here).

Creating and adding a new node to a linked list

It is difficult to understand how this node is being created, Can you please write step-wise what this set of code is actually doing, and what actions they represent?
void list::create_node(int value)
{
struct node *temp;// Please write in words the meaning of this statement
temp = new(struct node);// is this a dynamic node? )
temp->info = value;// is this value being assigned to this node?
if (last == NULL)// what is this set of code testing??
{
last = temp;// who is this last; the node which has been created?
temp->next = last; // is the node pointing to itself being only one node?
}
else
{
temp->next = last->next;((( // What is this statement saying?
last->next = temp;// What is this statement saying?
last = temp;// What is this statement saying?
}
}
void list::create_node(int value)
{
The above line declares a function that creates a node with the given value and inserts the node into the list. The code must be examined to see where the new node is inserted.
struct node *temp;
Declares a pointer to a node. The memory has not been allocated yet, only a pointer that will be used later.
temp = new(struct node);
Allocates memory for a node from the dynamic (runtime) memory area (a.k.a. heap). Calls the constructor of the node structure to initialize the memory, if a constructor exists.
The pointer temp is now pointing to the node object.
temp->info = value;
This assigns the value to the data field, info. Need the declaration of struct node in order to confirm this guess.
if (last == NULL)
{
Assuming that last is a pointer and points to the last node, this check is looking for an empty list. Common implementation is to have pointer values set to null to mark the end of the list.
last = temp;
temp->next = last;
}
The above code inserts the new node as the last node. The last pointer allows fast access to the end of the list. This allows for reverse iteration without having to traverse all the links to find the last node.
Some implementations set the next field to null to indicate the end of the list, others like this one, make it point to the last node.
else
{
temp->next = last->next;
At this point, the list is not empty.
The new node is made to point to the same node that the last node points to.
This is best understood by drawing the node boxes and arrows pointing to the nodes.
last->next = temp;
Updating the last node to point to itself. See the above section.
last = temp;
Updating the pointer to the last (end of list) node to point to the new node.
}
}
I suggest you draw the linked list and walk through this algorithm a couple of times to see how it works. Also review the singly linked list data type.
The circular reference of the last node may be confusing to you. This may not be the standard implementation that most books describe, but it is valid.