I want to find the max element in the linked list using recursion but my code doesn't work. I couldn't add the first element to the linked list to compare.
Here is my code:
void findmax(list L,int &m)
{
if(L!=NULL)
{
if(L->next!=NULL)
if(L->Data<L->next->Data)
m=(m>L->next->Data)?m:L->next->Data;
else
m=(m>L->Data)?m:L->Data;
else m=L->Data;
findmax(L->next,m);
}
else
return;
}
algorithm :
1> START //AFTER CREATING THE LINK LIST
2> MAX= START->DATA
3> TEMP=START //TEMPORARY NODE
4> START=NODE
5> THE CONTROL CHECKS WHETHER TEMP.DATA>MAX IF YES IT ASSIGNS TEMP.DATA TO MAX 6> OTHERWISE GOTO STEP 7 TO ITERATE
7> TEMP=TEMP.LINK //TRAVERSING THE LIST
8> WHILE(TEMP.LINK!=NULL)
9> TEMP=NULL
10> END
Related
I am currently solving the problem of creating a singly linked list using pointers in Free Pascal. The task:
Write a program that reads integers from the standard input stream until the "end of file" situation occurs, after which it prints all the entered numbers TWICE in the order in which they were entered. The quantity of numbers is not known in advance, explicit restrictions on this number are prohibited.
In my program, the list is built in the wrong order. How to build the correct sequence?
program InputStreamNumbers;
type
itemptr = ^item;
item = record
data: Integer;
next: itemptr;
end;
var
first, tmp: itemptr;
n: Integer;
begin
first := nil; { make the list properly empty! }
while not SeekEof do { number reading loop }
begin
read(n);
new(tmp); { created }
tmp^.data := n; { fill out}
tmp^.next := first;
first := tmp; { include in the list}
end;
tmp := first; { go through the list from beginning to end }
while tmp <> nil do
begin
writeln(tmp^.data);
tmp := tmp^.next; { move to the next element}
end;
end.
When you add nodes to the list, you create a new node named tmp and assign its data. That's correct. But there is an error in how you add new items to the list. The error is in
tmp^.next := first; // this creates the backwards linkage
first := tmp;
If you can (assuming it's not against your task), add one variable more
last: itemptr;
which, as the name says, refers to the last item in the list.
The purpose is to have direct access to the end of the list, to make it easier to add items. Otherwise you would need to traverse the list from the beginning until you find the last item ( who's item.next is nil).
The list should end up like this:
first last
| |
v v
item.next -> item.next -> item.next -> item.next = nil
.data .data .data .data
I leave the implementation for you to do. But if it helps, initially first and last are nil. After one item is created, both first and last point to that one item. After a second item is created, first still points to the first created, but last points to the second ... and so on.
Is there an easy way to understand when you can just call the recursive method vs having to set that recursive method to a variable?
For example...
Just calling the recursive function to traverse:
self.recurse(node.left)
self.recurse(node.right)
Having to set the recursive function to node.left and node.right:
node.left = self.recurse(node.left)
node.right = self.recurse(node.left)
Another example is to delete a node in a bst you have to set the recursive function to root.left and root.right... I get it but not completely... is there a easy way to understand when you can just call the recursive function vs having to set it to node.left, node.right..etc...?
def deleteNode(self, root: TreeNode, key:int) -> TreeNode:
if not root:
return root
if key < root.val:
root.left = self.deleteNode(root.left,key)
elif key > root.val:
root.right = self.deleteNode(root.right,key)
else:
if not root.left:
return root.right
elif not root.right:
return root.left
root.val = self.successor(root.right)
root.right = self.deleteNode(root.right,root.val)
return root
To understand this two above scenarios (Simple Recursive Call and Set result of Recursive call to a Variable), just try to understand the following code/function.
Let's say, you have a TREE, which contains a value in every node where value is either negative or positive. Now let's say, you are going to count how many nodes are there whose value is Positive.
The TREE structure for this problem is like following:
TREE{
Integer val;
TREE left = right = null;
}
Now you gave me this problem to solve. And I wrote a function/method which will count nodes with positive value. The function is following:
Integer countNodes(TREE node){
if(node == null){
return 0;
}else{
Integer count = 0; // which will count how many nodes are there with positive value
if(node.val >= 0){
count += 1; // if the value is positive I incremented count
}
// and we are checking every other nodes present in the TREE
getCount(node.left);
getCount(node.right);
// and return the final result
return count;
}
}
Now I returned my function to you, and you executed! But what! There is a big WRONG! It's giving wrong result, over and over again!!
But why???
Let's analysis.
if(node.val >= 0){
count += 1;
}
Up to that we were right! But the problem was, we were incremented the count, but wasn't use it! Each time we was calling function recursively, a new stack frame was created, a new variable named "count" was created, but we were not using this value!
To use the variable "count", we need to re-initialize the returned value of every recursive call to the variable, that's the way we can keep a link between the current stack-frame and the previous stack-frame and the previous of previous stack-frame and goes onn!.. we need to change little-bit in the function countNodes like following:
if(node.val >= 0){
count += 1;
}
count += getCount(node.left); // re-initialize count in each recursive call
count += getCount(node.right); // re-initialize count in each recursive call
return count;
Now everything we'll be alright! this code will work perfectly!
The above scenarios is implies your problem.
self.recurse(node.left)
self.recurse(node.right)
this is nothing but simple traversing over all the nodes.
But if you need to use the returned result of every recursion, you need to initialize/re-initialize the returned value to a variable. That's what is happening with:
node.left = self.recurse(node.left)
node.right = self.recurse(node.left)
I HOPE this long (bit long) explanation will help to go further. Happy Coding! : )
I am new to Linked List. I am trying to write a CopyList() code that can copy a linked list to a new list. There's a unique version using recursive and I don't really understand:
struct node
{
int data;
struct node *next;
};
struct node* CopyList(struct node* head) {
struct node* current = head;
if (current == NULL) return NULL;
else {
struct node* newList = malloc(sizeof(struct node));
newList->data = current->data;
newList->next = CopyList(current->next); // recur for the rest
return(newList);
}
}
My trouble of understanding is the line newList->next = CopyList(current->next);
So how does this work for copying and why?
Lets take an example. If you simply put the current->next in newList->next
i.e
newList->next = current->next. Then it will point to the next node of old list only. Not to the next node of new list.
So to make a different list (Copy list). You separately have to make a new node and return it to point to next of previous node.
This is the magical recursive statement.
newList->next = CopyList(current->next);
For each recursive step, this will delegate the task of creating remaining linked list, to the next recursive call.
For example: List is getting created from right to left.
CopyList (1->2->3->4->5)
|
|---------1-> CopyList (2->3->4->5)
|
|---------2-> CopyList (3->4->5)
|
|---------3-> CopyList (4->5)
|
|---------4-> CopyList (5)
|
|---------5-> CopyList (NULL)
Returns 5
Returns 4->5->NULL
Returns 3->4->5->NULL
Returns 2->3->4->5->NULL
Returns 1->2->3->4->5->NULL
As per wiki
A simple base case (or cases)—a terminating scenario that does not use recursion to produce an answer.
A set of rules that reduce all other cases toward the base case.
In your case, terminating scenario is if list reaches the end, just return null and a new node is created at every step that leads the list to the base scenario.
This is the recursion step. The previous two commands create a new node and copy the head of the current list to that object. Now, instead of iterating (looping) through the rest of the list, we call CopyList to copy the remainder of the list -- everything except the head node that we just copied.
CopyList returns a copy of that remainder, which we simply append to the copy of the head node ... and we're done.
Following are 2 codes:
1. Find the kth smallest integer in a binary search tree:
void FindKthSmallest(struct TreeNode* root, int& k)
{
if (root == NULL) return;
if (k == 0) return; // k==0 means target node has been found
FindKthSmallest (root->left, k);
if (k > 0) // k==0 means target node has been found
{
k--;
if (k == 0) { // target node is current node
cout << root->data;
return;
} else {
FindKthSmallest (root->right, k);
}
}
}
Find the number of nodes in a binary tree:
int Size (struct TreeNode* root)
{
if (root == NULL) return 0;
int l = Size (root->left);
int r = Size (root->right);
return (l+r+1);
}
My Question:
In both these codes, I will have to keep track of the number of nodes I visit. Why is it that code 1 requires passing a parameter by reference to keep track of the number of nodes I visit, whereas code 2 does not require any variable to be passed by reference ?
The first code (1) is looking for the smallest node in your BST. You search from the root down the left side of the tree since the smallest valued node will be found in that location. You make several checks:
root == null - to determine if the tree is empty.
k == 0 - zero in this case is the smallest element. You are making this assumption based on whatever principles are apart of this tree.
Then you recursively traverse the list to find the next smallest in the left side of the tree. You perform one more check that if k > 0 you decrement k <- this is why you need to pass by reference since you are making changes to some value k given by a separate function, global variable, etc. If k happens to be zero then you have found the smallest valued node, if not you go one right of the current node and then continue the process from there. This seems like a very arbitrary way of finding the smallest node...
For the second code (2) you are just counting the nodes in your tree starting at the root and counting each subsequent node (either left or right) recursively until no more nodes can be found. You return your result which is the total amount of left nodes,right nodes. and + 1 for the root since it was not counted earlier. In this instance no passed by reference variable is needed although you could potentially implement one if you choose to do so.
Does this help?
Passing the parameter by reference allows you to keep track of the count within the recursive process, otherwise the count would reset. It allows you to modify the data within the memory space, thus changing the former value not the current/local value.
in groovy loop like :
x = [1,2,3,4,5]
x.each { i ->
// other CRUD type functionality - required
// print each values - not required
}
Can I restrict the print values inside the each clause. Actually I want the CRUD functionality to execute. But after that print i prints each values which I don't want.
my output as of now :
1
2
3
4
5
6
==>1
==>2
==>3
==>4
==>5
==>6
Or, use findAll to just then work on a list of interest:
[1,2,3,4,5].findAll { it % 2 == 0 }.each { println it }
Will just print the even numbers for example
Edit
Hang on, do you mean in the groovy console where it shows you the return value of the script in inverse type?
each returns the list it worked on, so you'll see the list after execution.
You can stop this by putting null at the end of your script (or something that returns null such as println "done")
Use a return statement in the end of the script.
x = [1,2,3,4,5]
x.each{println it}
return
Return from the closure to skip elements:
def list = [1, 2, 3, 4, 5, 6]
list.each { i ->
// skip uneven values
if (!(i % 2 == 0)) return
println i
}
Not that the return just skips the iteration step and does not return from the function the code is executed in.