I used NodeCallback to get variable branch with this code:
ILONODECALLBACK0(myVB){
for (int i = 0; i < getNnodes(); i++) {
cout << "BranhVariable_" << getBranchVar(i) << endl;
}
}
And the output is:
I can't verify the output details. I expect one variable selected for branching at each node but it shows more than one variable.
Also after twenty nodes I got error 1006.
It seems you are going with the default node display frequency? That shows a log line only every N nodes (and between two log lines there may be more than one branch). So you may have to set the MIPDisplay parameter to 1.
Also, the node callback is invoked whenever a node has to be selected (so more or less at each not in the tree). But then it always prints the branch variable for every open node. If you want to see the branching variable for the node about to be selected then print it only for the first node (the node that CPLEX would choose is at index 0, the order of the rest of the node list is unspecified).
Related
I'm new to the data structures and recursion concept. I'm struggling to understand why and who he was able to use the recursion in this concept. I found this code in the forums for this and I couldn't really understand the concept of this. For simple case of 2 1 3 4, if any one can explain the iteration steps, it will be greatly appreciated on my behalf.
Here is the link for hacker rank:
https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list
Node SortedInsert(Node head,int data) {
Node n = new Node();
n.data = data;
if (head == null) {
return n;
}
else if (data <= head.data) {
n.next = head;
head.prev = n;
return n;
}
else {
Node rest = SortedInsert(head.next, data);
head.next = rest;
rest.prev = head;
return head;
}
}
Recursion:
Recursion means a function calls itself. It is used as a simple way to save state information for algorithms that require saving of multiple states, usually a large number of states, and retrieving them in reverse order. (There are alternative techniques that are more professional and less prone to memory issues, such as using a Stack object to save program state).
This example is poor but typical of intro to recursion. Yes, you can iterate through a linked list using recursion but there is absolutely no reason to. A loop would be more appropriate. This is purely for demonstrating how recursion works. So, to answer your question "Why?" it is simply so you can learn the concept and use it later in other algorithms that it actually makes sense.
Recursion is useful when instead of a linked list you have a tree, where each node points to multiple other nodes. In that case, you need to save your state (which node you are on, and which subnode you called last) so that you can traversing one of the linked nodes, then return and go to the next node.
You also asked "how". When a function calls itself, all of its variables are saved (on the program stack) and new ones are created for the next iteration of itself. Then, when that call returns, it goes back to where it was called from and the previous set of variables are loaded. This is very different from a "jump" or a loop of some kind, where the same copies of the variables are used each time. By using recursion, there is a new copy of every local variable each time it is called. This is true even of the "data" variable in the example, which never changes (hence, one inefficiency).
I've created a 'pop' method to take the last node off of a linked list. However, the issue I'm receiving is that it's not removing the node, it's simply telling me the data in the node that should be removed.
I should preface with I'm using test driven development and the test was written to say 'assert_equal "blop", list.pop. "blop" is the value of the last node. It's great that I got my method to tell me that, but it still doesn't remove the node.
def pop
#count -= 1
return_string = ""
current_node = #head
until current_node.next_node == nil
current_node = current_node.next_node
end
return_string << current_node.data + " "
return_string.strip
current_node.next_node = Node.new(data)
end
My question is how do I return the value of what's being removed, as well as, removing the value from the linked list.
until current_node.next_node == nil
current_node = current_node.next_node
end
When that loop finishes, current_node is pointing to the last node (the node for which the next node is `nil).
That's the node you should remove, but in order to remove that one, you should point the previous node's next_node to nil.
However, at that point you don't have a reference to the previous node.
You could have another variable to track the previous node so that you can then remove it once you exit the loop.
You can check this related question (not Ruby specific) for ideas on the algorithm.
Linked List implementation for a stack
As a side note, one of the answers on that one implements this as making pop remove the first node of the list (and push add the node to the beginning), which makes it easier (and faster, since you don't go over the whole list each time).
I have homeowork to write pseudo code to check if a valid binary tree is a search binary tree.
I created an array to hold the in-order values of the tree. if the in-order values are in decreasing order it means it is indeed BST. However I've got some problem with the recursion in the method InOverArr.
I need to update the index of the array in order to submit the values to the array in the order they are at the tree.
I'm not sure the index is really updated properly during the recursion.. is it or not? and if you see some problem can you help me fix this? thanks a lot
pseudo code
first function
IsBST(node)
size ← TreeSize(node)
create new array TreeArr of Size number of cells
index ← 0
few comments:
now we use the IN_ORDER procedure with a small variation , I called the new version of the procedure: InOrderArr
the pseudo code of InOrderArr is described below IsBST
InOrderArr(node, TreeArr, index)
for i from 1 to size-1 do
if not (TreeArr[i] > TreeArr[i-1]) return
false
return true
second function
InOrderArr (node, Array, index)
if node = NULL then return
else
InOrderArr (node.left, Array, index)
treeArr[index] = node.key
index ← index + 1
InOrderArr (node.right, Array, index)
Return
Your code is generally correct. Just three notes.
The correctness of the code depends on the implementation, specifically on the way of index handling. Many programming languages pass arguments to subroutines by value. That means the subroutine receives a copy of the value and modifications made to the parameter have no effect on the original value. So incrementing index during execution of InOrderArr (node.left, Array, index) would not affect the position used by treeArr[index] = node.key. As a result only the rightmost path would be stored in the array.
To avoid that you'll have to ensure that index is passed by reference, so that incrementation done by a callee advances the position used later by a caller.
BST is usually defined so that the left subtreee of a node contains keys that are less than that node's key, and the right subtree contains nodes with greater keys – see Wikipedia's article on BST. Then the inorder traversal retrieves keys in ascending order. Why do you expect descending order?
Possibly it would be more efficient to drop the array and just recursively test a definition condition of BST?
Whenever we follow a left link we expect keys which are less than the current one. Whenever we follow the right link we expect keys greater the the current one. So for most subtrees there is some interval of keys values, defined by some ancestor nodes' keys. Just track those keys and test whether the key falls inside the current valid interval. Be sure to handle 'no left end defined' condition on the letfmost path and 'no right end' on the rightmost path of the tree. At the root node there's no ancestor yet, so the root key is not tested at all (any value is OK).
EDIT
C code draft:
// Test a node against its closest left-side and right-side ancestors
boolean isNodeBST(NODE *lt, NODE *node, NODE *rt)
{
if(node == NULL)
return true;
if(lt != NULL && node->key < lt->key)
return false;
if(rt != NULL && node->key > rt->key)
return false;
return
isNodeBST(lt, node->left, node) &&
isNodeBST(node, node->right, rt);
}
boolean isTreeBST(TREE *tree)
{
return isNodeBST( NULL, tree->root, NULL);
}
This is a question posed to me in an interview.
"A single linked list is there in the memory. You have to delete a node. You need to write a function to delete that node, which takes only the address of the node to be deleted as input and nothing else(including head)"
I gave the answer similar to the one answered in the below post -- Copying the contents of the next node into the node to be deleted and deleting the next one.
Deleting a middle node from a single linked list when pointer to the previous node is not available
But the interviewer asked me again, what if I pass the address of the last node. I told him, since the next will be a NULL, copy that NULL into the data field along with the address to the next node which is also NULL. Then he told me there will be a problem of dangling pointers... which I didn't understand a bit. Can some one please throw light into this problem ? Is there a generic solution to this ?
Update (Two days later) : A little bit additional. Considering there is no special node at the end of the list. And the last node points to NULL and if that node is given as input, how to make the before last node point to NULL. Or is it impossible ?
Simply put : If a node is given as input to a function, how to make the pointer that references it, point to NULL
Steps:
Copy data from Node(i+1) to Node(i)
Copy the NEXT of second Node(i+1) into a temporary variable.
Now Delete the second Node(i+1) // it doesn't require pointer to the previous node.
Function:
void delete_node(node* node)
{
node->Data = node->Next->Data;
node* temp = node->Next->Next;
delete(node->Next);
node->Next = temp;
}
Dangling Pointer:
(http://en.wikipedia.org/wiki/Dangling_reference)
Dangling pointers and wild pointers in computer programming are
pointers that do not point to a valid object of the appropriate type.
These are special cases of memory safety violations.
Dangling pointers arise when an object is deleted or deallocated,
without modifying the value of the pointer, so that the pointer still
points to the memory location of the deallocated memory. As the system
may reallocate the previously freed memory to another process, if the
original program then dereferences the (now) dangling pointer,
unpredictable behavior may result, as the memory may now contain
completely different data.
In your answer, to delete the given node you actually delete the next node, which might be being referenced by a pointer. That's how dangling pointer problem arise.
(1) There are no outside references to the list, as you clarify in a note.
(2) Dangling pointer problem can arise, as the interviewer said.
Both (1) and (2) cannot be correct at the same time. Which means there is a misunderstanding somewhere.
About Deleting the Last Node:
But the interviewer asked me again, what if I pass the address of the
last node. I told him, since the next will be a NULL, copy that NULL
into the data field along with the address to the next node which is
also NULL.
I think you are confusing these two things: (1) A pointer p that points to NULL, (2) A linked list node that has NULL in its data field.
Suppose the data structure is a -> b -> c -> d. Writing NULL to d's data field will not magicly make c to have a NULL pointer in its next field.
You can delete the last node if the linked list always has a special last node that will never be deleted. For example, a -> b -> c -> d -> LAST where LAST has a special value in its data field that denotes it is really the last element. Now to delete d, you could delete LAST and write the special value in d's data field.
Maybe these are exactly what you tried to tell during the interview, in which case there must have been some miscommunication between you and the interviewer.
Then there should be a check in the program whether the given node is the last node or not.
void delete_node(node* node1) {
node* search=head;
if(node1==head) {
head=head->next;
search->next=NULL;
node1->next=NULL;
}
while(search->next != node1)
search=search->next;
if(node1->next==NULL) {
search->next=NULL;
} else {
search->next=node1->next;
node1->next=NULL;
}
delete node1;
}
If there are other elements that are pointing to the next node which will be copied to the current node and then deleted, then this operation will introduce a bug. So in your answer you should have emphasized that your solution only works if there are no outside references to the list.
Your solution works with the last node only if the data structure is augmented with a specific "last node" element. (If you are using Smalltalk, you can write self become: nil No other language has anything similar)
No, there is no generic solution if there are outside references to the list. I think the interviewer wanted to see whether you are really knowledgable in the subject matter or were just repeating a memorized answer.
Probably your link list traversing might need to assume that any node that points to null is null node regardless of the value...
a->b->c->d->NULL
so d is null node and the node should not be considered as a node. this way you can save on using special values since they are not correct in a generic sense. other than that you will not have any other way for previous node to point to null.
When the last node is given, instead of deleting it, assign it to a dummy node and while displaying the data we can check for ptr->next as dummy node and terminate there.
In case of dangling pointer, I believe when the pointer is freed(deallocated), it will become dangling pointer and so after freeing assign it to NULL.
Below will be my code snippet for this Question:
dummy-> data = NULL;
dummy-> next = NULL;
FUNC(del_ptr)
{
if (del_ptr->next == NULL )
{
del_ptr = dummy;
return;
}
struct node *next = del_ptr ->next;
del_ptr -> data = next -> data;
del_ptr -> next = next -> next;
free(next);
next=NULL;
}
Assumption: deleteNode() has reference to node pointer.
Simple solution without a while loop. In deleteNode(), if case handles deletion of head and intermediate node and else handles deletion of last node.
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int d): data(d){}
};
void insert(Node* &head, int data){
Node *node = new Node(data);
node->next = head;
head = node;
}
void print(Node *head){
Node *temp = head;
while(temp !=NULL){
cout << temp->data <<" ";
temp = temp->next;
}
cout << endl;
}
void deleteNode(Node *&node){
cout << "Deleting "<<node->data<<endl;
if(node->next != NULL){
Node *t = node->next;
node->data = node->next->data;
node->next = node->next->next;
delete t;
}else{
delete node;
node = NULL;
}
}
int main(int argc, char const *argv[]) {
Node *head = NULL;
insert(head, 10);
insert(head, 20);
insert(head, 30);
insert(head, 40);
insert(head, 50);
print(head);
deleteNode(head->next); //delete 40
deleteNode(head->next->next->next); //delete last node 10
print(head);
return 0;
}
public void removeNode(Node node){
/* if no node return null */
if(node==null) return;
/* if only 1 node then delete node */
if(node.getNext()==null) {
node = null;
return ;
}
/* copy next node data to this node */
node.data = node.getNext().data();
/* store the next next node */
Node second = node.getNext().getNext();
/* remove next node */
removeNode(node.getNext());
/* set the copied node as next */
node.setNext(second);
}
I'm having a hell of a time trying to figure this one out. Everywhere I look, I seem to be only running into explanations on how to actually traverse through the list non-recursively (the part I actually understand). Can anyone out there hammer in how exactly I can go through the list initially and find the actual predecessor/successor nodes so I can flag them in the node class? I need to be able to create a simple Binary Search Tree and go through the list and reroute the null links to the predecessor/successor. I've had some luck with a solution somewhat like the following:
thread(node n, node p) {
if (n.left !=null)
thread (n.left, n);
if (n.right !=null) {
thread (n.right, p);
}
n.right = p;
}
From your description, I'll assume you have a node with a structure looking something like:
Node {
left
right
}
... and that you have a binary tree of these set up using the left and right, and that you want to re-assign values to left and right such that it creates a doublely-linked-list from a depth first traversal of the tree.
The root (no pun intended) problem with what you've got so far is that the "node p" (short for previous?) that is passed during the traversal needs to be independent of where in the tree you currently are - it always needs to contain the previously visited node. To do that, each time thread is run it needs to reference the same "previous" variable. I've done some Python-ish pseudo code with one C-ism - if you're not familiar, '&' means "reference to" (or "ref" in C#), and '*' means "dereference and give me the object it is pointing to".
Node lastVisited
thread(root, &lastVisisted)
function thread(node, lastVisitedRef)
if (node.left)
thread(node.left, lastVisitedRef)
if (node.right)
thread(node.right, lastVisitedRef)
// visit this node, reassigning left and right
if (*lastVisitedRef)
node.right = *lastVisitedRef
(*lastVisitedRef).left = node
// update reference lastVisited
lastVisitedRef = &node
If you were going to implement this in C, you'd actually need a double pointer to hold the reference, but the idea is the same - you need to persist the location of the "last visited node" during the entire traversal.