Infinite loop : Process not terminating properly - infinite-loop

struct node
{
int data;
node* left;
node* right;
};
int secondlargest(struct node* a)
{
while(a->right != NULL){
secondlargest(a->right);
}
return a->data;
}
I am not able to trace where have I done the mistake and why its not coming out of the while loop.

Your mistake is that you shouldn't use an while but instead an if because it is recursive, but what do you want the function to return? the data of the last member? if so it should be like this:
int secondlargest(struct node* a) {
if(a == NULL) return -1;
secondlargestr(a);
}
int secondlargestr(struct node* a) {
if(a->right!=NULL) return secondlargest(a->right);
return (a->data);
}

If you insist on the recursive version, change the while to if.
int secondlargest(node* a)
{
if(a == null){
// if the first node is already NULL
return -1;
}
if(a->right == NULL){
return a->data;
}else{
return secondlargest(a->right);
}
}
Basics of recursion:
Must have base case
Break down problem size recursively
If you want the iterative way:
int secondlargest(node* a)
{
node* temp = a;
int data = -1;
while(temp != null){
data = temp->data;
temp = temp->right;
}
return data;
}

Related

When finding cycles in undirected graphs, why can't we just keep track of previous parent node while using BFS traversal

Basically when we use DFS we just check if the adjacent nodes for a newly visited node have been already visited and they are not the parent node which made the DFS call for this node. If this is the case cycle is present.
I was using similar thing for BFS while keeping track of previous parent node and my logic doesn't seem to work. The test case on which my code is failing is too big to understand the problem. Can anyone let me know where my logic is broken? Thank you in advance
bool bfs(vector<int> adj[], bool isVisited[], int s, int V)
{
queue<int> q;
q.push(s);
isVisited[s] = true;
int parent = s;
int prevParent = -1;
while(q.empty() == false)
{
int u = q.front();
prevParent = parent;
parent = u;
q.pop();
for(int i = 0 ; i < adj[u].size() ; i++)
{
if(isVisited[adj[u][i]] == false)
{
isVisited[adj[u][i]] = true;
q.push(adj[u][i]);
// parent[][i]] = u;
}
else
{
if(adj[u][i] != prevParent)
return true;
}
}
}
return false;
}
bool isCycle(int V, vector<int> adj[]) {
// Code here
bool isVisited[V] = {false};
for(int i = 0 ; i < V ; i++)
{
if(isVisited[i] == false)
if(bfs(adj, isVisited, i, V) == true)
{
return true;
}
}
return false;
}

Conditional jump or move depends on uninitialised value(s) in LinkedList

I keep getting the Conditional jump or move depends on uninitialised value(s) in Valgrind for the function printList() and freeList(). I read a few posts and the problem was because head was not initialized after malloc() so I added newList->head = NULL after malloc in my createList() function. I am not sure how to fix this error. Any help is really appreciated! I am really new to C so I really don't know what the problem is...
typedef struct node{
int year;
int win;
struct node* next;
}node_t;
typedef struct slist{
node_t* head;
int size;
}slist_t;
node_t* makeNode(int year, int win){
node_t* newNode = (node_t*) malloc(sizeof(node_t));
if (newNode == NULL){
return NULL;
}
newNode->year = year;
newNode->win = win;
return newNode;
}
void freeNode(node_t* node){
if (node == NULL){
return;
}
free(node);
}
slist_t* createList(){
slist_t* newList = (slist_t*) malloc(sizeof(slist_t));
if (newList == NULL){
return;
}
newList->head = (node_t*) malloc(sizeof(node_t));
newList->head = NULL;
newList->size = 0;
return newList;
}
node_t* addFirst(slist_t* list, int year, int win){
node_t* node = makeNode(year, win);
if (list == NULL){
return;
}
if (node == NULL){
return;
}
if (list->head == NULL){
list->head = node;
}
else{
node->next = list->head;
list->head = node;
}
list->size += 1;
return node;
}
void printList(slist_t* list){
if (list == NULL){
return;
}
node_t* itr = list->head;
while(itr != NULL){
printf("%d, %d wins\n", itr->year, itr->win);
itr = itr->next;
}
printf("\n");
}
void freeList(slist_t* list){
node_t* node = list->head;
while (node){
node_t* temp = node;
node = node->next;
free(temp);
}
free(list);
}
int main(){
slist_t* list = createList();
addFirst(list, 2014, 71);
addFirst(list, 2015, 78);
addFirst(list, 2016, 93);
addFirst(list, 2017, 93);
addFirst(list, 2018, 108);
printList(list);
freeList(list);
return 0;
}
The problem is that makeNode does not initialise newNode->next. If it happens to have the value 0 (NULL), things will go fine, but try to add this statement in makeNode and then run the program:
newNode->next = 1000000;
Now it is more likely you get a segmentation fault or some other weird behaviour. So add this line instead:
newNode->next = NULL;
Not your issue, but this sequence of assignments produces a memory leak:
newList->head = (node_t*) malloc(sizeof(node_t));
newList->head = NULL;
After having allocated memory, you immediately lose the reference to it, by overwriting that reference with NULL. You should just drop the first of these two assignments. The first node is created later, when you call addFirst, so no node should be allocated here.

code got strucked in a infinite loop when I tried to reverse a linked list using recursion

I was trying to reverse a linked list using recursion but when I tried to print out all the elements of the linked list at first it was printing out elements as expected but after printing out the last element it started printing the last and second last element repeatedly. I tried to debug it and I think the problem is that the last element is pointing towards the second last element whether it should be pointing towards NULL. I am not able to figure out what is wrong with my code so please help me out.
example- input 1,2,3,4,5,6
expected output 6,5,4,3,2,1
actual output 6,5,4,3,2,1,2,1,2 ...
#include<iostream>
using namespace std;
class node{
public:
int val;
node *next;
node(int val)
{
this->val = val;
this->next = NULL;
}
node(int val,node *next)
{
this->val= val;
this->next=next;
}
};
void insertAtTail(node *&head,int val){
node *n = new node(val);
if (head==NULL)
{
head = n;
return;
}
node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next=n;
}
void display(node *head)
{
node *n = head;
while (n!=NULL)
{
cout << n->val << "->";
n = n->next;
}
cout << "NULL" << endl;
}
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
int main()
{
node *head = NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
insertAtTail(head,4);
insertAtTail(head,5);
insertAtTail(head,6);
display(head);
node *newhead = reverseRecursive(head);
display(newhead);
return 0;
}
There is a bug in function reverseRecursive().
Line head->next == NULL; should be head->next = NULL;
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL; // <<< should be head->next = NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
Not sure which compiler you were using, but this statement will typically generate a warning.

Tree returning the maximum value

50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood.
The recursive function should look something like this:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
Full code:
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}

strange behaviour of cout?

In a long assignment I found a miraculous behaviour of cout!!
`
for(i=0; i<ndel; i++)
{
cin>>a;
head=Delete(head, a);
cout<<"Deleting ";
cout<<a<<endl;
//cout<<"Deleting "<<a<<endl; /*this gives seg error*/
printInts(head);
}
`
The code works fine with
cout<<a<<endl;
but gives a segmentation fault with
cout<<"Deleting "<<a<<endl;
Here's my Delete function:
node* Delete(node *T, int a)
{
if(a==1 && T!=NULL)
{
T->flag=0;
return T;
}
int arr[50];
int n, i, tr_num; /* tr_num is the index of array corresponding to last node not to be deleted if the no. to be del is leaf*/
node *tr, *ptr; /*tr istracker on last pointer that cannot be deleted if it encounters leaf*/
node *pth[50];
n=find_binary(arr, a);
tr=T;
ptr=T;
pth[0]=T;
tr_num=0;
for(i=0; i<n-1; i++)
{
if(arr[n-2-i]==0)
{
if(ptr->left==NULL)
{
return T;
}
ptr=ptr->left;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
if(arr[n-2-i]==1)
{
if(ptr->right==NULL)
{
return T;
}
ptr=ptr->right;
pth[i+1]=ptr;
if((ptr->flag==1 && (ptr->right!=NULL || ptr->left!=NULL)) || (ptr->right!=NULL && ptr->left!=NULL))
{
tr_num=i+1;
tr=ptr;
}
}
}
ptr->flag=0;
if(ptr->left==NULL && ptr->right==NULL)
{
for(i=n-1; i>=tr_num+1; i--)
{
delete pth[i];
pth[i]=NULL;
}
if(arr[n-tr_num-2]==1)
{
pth[tr_num]->right=NULL;
}
else if(arr[n-tr_num-2]==0)
{
pth[tr_num]->left=NULL;
}
}
return T;
}
Here's the find binary code..
int find_binary(int arr[], int num)
{
int i=0;
while(num!=0)
{
arr[i]=num%2;
num=num/2;
i++;
}
return i;
}
In another instance:
I have a function with prototype
node * search(node *T, int a);
calling this function in main
cout<<search(BT, 7);
works!
But
node *ptr=search(BT, 7);
gives segmentation error!! I am clueless why, because the similar assignment works completely fine in my delete function but in main it gives segmentation error!!
Note: node is a structure.
I compile using g++

Resources