Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Hi, I could run my code in my computer however the leetcode always says Runtime Error. Am I doing something wrong in memory? I ran the same case which leetcode said I was wrong.
I believe I checked all the corner cases.
input [1,2] output [2]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head) return head;
ListNode* tmp =head;
int size =1;
while(tmp->next){
tmp=tmp->next;
size++;
}
if(n>size) return head;
ListNode* prev = head;
//delete the head
if (n==size){
if(prev->next){
prev=prev->next;
delete head;
head = prev;
return head;
} else {
delete head;
return NULL;
}
}else {
for (int j=0; j<size-n-1; j++) {
prev = prev->next;
}
tmp=prev->next;
//if tail, delete, else reconnect.
if (tmp->next){
prev->next = tmp->next;
}
delete tmp;
return head;
}
}
};
Related
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;
}
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.
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;
}
Code :
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct list
{
int data;
struct list * next;//self referenced structure
}slist;
void displayList(slist * start)
{
slist * temp;
if(start==NULL)
{
printf("Empty Linked List");
return;
}
for(temp=start;temp!=NULL;temp=temp->next)
printf("%d ",temp->data);
return;
}
void insertLast(slist * * start,slist * node)
{
slist * temp;
if(start==NULL){
(* start)=node;
return;
}
temp=(* start);
while((temp->next)!= NULL)
temp=temp->next;
temp->next=node;
return;
}
int main()
{
int i,j;
//slist * node;
char Ans;
/*printf("Write the number of vertices\n");
scanf("%d",&N);*/
slist * start[N];
for(i=0;i<N;i++)
start[i]=NULL;
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
printf("Is there a connection between V[%d] and V[%d]\n",(i+1),(j+1));
scanf(" %c",&Ans);
if(Ans=='y'||Ans=='Y')
{
slist * node1=(slist *)malloc(sizeof(slist));
node1->data=(j+1); node1->next=NULL;
insertLast(&start[i],node1);enter code here
slist * node2=(slist *)malloc(sizeof(slist));
node2->data=(i+1); node2->next=NULL;
insertLast(&start[j],node2);
}
}
}
for(i=0;i<N;i++)
{
displayList(start[i]);
printf("\n");
}
return 0;
}
The above code is showing segmentation fault at the line where while((temp->next)!=NULL) is written whereas while creation of linked lists, the same insertLast worked just fine. What is the fault in the code?
Your program crashed as you are checking if start is NULL or not. But that does not guarantee that *start is also not NULL. In such situation, temp gets NULL and in while loop temp->next actually trying to access next element of NULL pointer and that is why the crash.
Changing this line -
if(start==NULL)
to
if(*start==NULL)
in insertLast() will fix the crash.
I also recommend to use a debugger like gdb to debug such issues.
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++