Below is code for inserting a node at the end of a linked list. I am getting a segmentation fault. Please help!!
Node* Insert(Node *head,int data)
{
struct Node *last=head;
struct Node* n=(struct Node*)malloc(sizeof(struct Node));
n->data=data;
n->next=NULL;
if(head==NULL)
{
head=n;
}
while(last->next!=NULL)
{
last=last->next;
}
last->next=n;
return 0;
}
Your function is returning the numeric literal 0, but its return type is "Node *", so as soon as you try to use the return value of the function, you're headed for trouble.
What did you intend to return? The head of the modified list? Or the newly-appended Node? Either way, it's not returning them.
Related
i'm trying to implement binary tree, pre order traversal using stack.
here its popping the last left node and after that root=root->right doesnt seem to work. Pls help. here 7 is being popped out and is being displayed and after the the program is ending.
all the functions are working yet not the desired output
#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
int a[maxsize];
int top=-1;
struct node{
int data;
struct node *left, *right;
};
struct node *newNode(int data)
{
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
if(!nn)
return;
nn->data=data;
nn->left=nn->right=NULL;
return nn;
};
void push(struct node *root)
{
printf("pushcalled\n");
if(top!=maxsize-1)
a[++top]=root;
}
int isempty()
{
return(top==-1);
}
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
void deleteStack()
{
free(a[top--]);
}
void preorder(struct node *root)
{
while(1)
{
while(root)
{
printf("%d\t",root->data);
push(root);
root=root->left;
}
printf("hello\n");
if(isempty())
break;
printf("hello\n");
root=pop();
printf("Popped data is:%d\n",root->data);
root=root->right;
printf("right data is:%d\n",root->data);
}
deleteStack();
}
int main()
{
int data;
struct node *root=newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
preorder(root);
return 0;
}
Your logic is correct but there are some errors in your code.
root=root->right;
printf("right data is:%d\n",root->data);
you should check whether the root is null or not before you try to access root->data. That is why you are getting a segmentation fault. So put a condition if(root!=NULL) above printf() statement.
Another mistake is in the implementation of stack's pop.
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
return a[top];
top--;
}
}
it should be like this,
struct node *pop()
{
printf("popcalled\n");
if(top!=-1)
{
struct node* temp = a[top];
top--;
return temp;
}
}
In your code, when you return a[top]; the line below it i.e. top--; never executes and the value of top remains same.
i am trying to connect the nodes of a binary tree that are at the same level
i am using a queue to do it. initially i have pushed the root into queue. but in line 12 when the first if statement is executed that is
if(q.front()->left!=NULL) then i am getting a runtime error.
please help
node structure:
struct node
{
int data;
struct node* left;
struct node* right;
struct node* nextRight;
};
function to connect the nodes
node* connect(node* root)
{
if(root=NULL)
return display(root);
queue<node*> q;
int count=0;
q.push(root);
count++;
while(!q.empty())
{
cout << "inside while loop\n";
int i=1,temp=0;
while(i<=count)
{
cout << "inside inner while\n";
if(q.front()->left!=NULL)
{
cout << "inside if 1\n";
q.push(q.front()->left);
temp++;
}
if(q.front()->right!=NULL)
{
cout << "inside if 2\n";
q.push(q.front()->right);
temp++;
}
node* v=q.front();
q.pop();
if(i==count)
v->nextRight=NULL;
else
v->nextRight=q.front();
}
count=temp;
}
return display(root);
}
You need to make lot of changes in your code.
Mistake 1:
while(i<=count)
will never be true.
Mistake 2:
v->nextRight=q.front();
will set the nextRight to point to Left child.
Mistake 3:
i is never changing, then why declare a variable and create confusion.
Insert Node in a doubly sorted linked list After each insertion, the list should be sorted
Node is defined as
struct Node
{
int data;
Node *next;
Node *prev;
}
And a logic of function is written below..
Node* SortedInsert(Node *head,int data)
{
// Complete this function
// Do not write the main method.
struct Node *newn= (struct Node*)malloc(sizeof(struct Node*));
newn->data= data;
newn->next= newn->prev= NULL;
struct Node *trav=head, *pre=NULL;
if(head==NULL)
head= newn;
else if(newn->data <= trav->data)
{
newn->next= trav;
trav->prev= newn;
head= newn;
}
else
{
while(trav->data <= newn->data)
{
pre= trav;
trav=trav->next;
}
pre= trav;
trav=trav->next;
newn->next= trav;
trav->prev= newn;
pre->next= newn;
newn->prev= pre;
}
return head;
}
please let me know what is problem with the logic
You are making a small mistake,first of all the space is allocated this way:
struct Node *newn= (struct Node*)malloc(sizeof(struct Node));
and the right else condition is:
else
{
while(trav!=NULL&&trav->data <= newn->data)
{
pre= trav;
trav=trav->next;
}
newn->prev=pre;
newn->next=trav;
pre->next=newn;
if(trav!=NULL)
trav->prev=newn;
}
The detailed question is to find all the nodes with distance x( i.e. number of edges =x) from a given node .
I was asked in an Amazon Interview today,
void findNodeWithDistanceX(struct node* root,struct node * qnode, int value)
{
//root is root Node, qnode is questionnode from which distance to be calculated, value is the
//distance to be calculated
//finding distance between root and qnode
int distance = findDistancefromRoot(root ,qnode);
if(distance> value)
{
traverseDistancedown(root ,distance-value);
}
if(distance ==value){
printf("%d",root->value);
}
// Traverse and find all nodes with distance value from 'qnode' down the tree
traverseDistancedown(qnode,value);
Now In case of finding the distance "value" from qnode .
I did not get the answer how to traverse up the Tree and satisfy the condition of distance with value.
Although many cases arises here.
I tried backtracking from qnode but to no avail I was unable to impress him and unable to write the Code.
Any Discussion regarding implementing the traversal up the tree will be helpful to me.
The simplest way is with a depth-first search, keeping track of the distance as you go along. It's a simple pre-order traversal starting at the "question node".
void nodesAtDistance(struct node* qnode, int requestedDistance, int currentDistance)
{
if (qnode == null) return;
if (currentDistance == requestedDistance)
{
// output qnode
// and then return because children are further away
return;
}
// visit left and then right
nodesAtDistance(qnode->left, requestedDistance, currentDistance+1);
nodesAtDistance(qnode->right, requestedDistance, currentDistance+1);
}
So if you call this with:
nodesAtDistance(myNode, 5, 0);
It will output all nodes that are 5 levels below myNode.
Now, if I were to write this as an API function, I would provide an overload that doesn't require the client to pass that currentDistance parameter. Because if somebody were to write nodesAtDistance(myNode, 5, 1), you'd get things at distance 4. So, create this overload:
void nodesAtDistance(node * qnode, int requestedDistance)
{
nodesAtDistance(qnode, requestedDistance, 0);
}
Make that function publicly visible, and make the other one private.
try this code, although this code checks only for children nodes and does not go back to check on ancestors nodes at given distance
#include<stdio.h>
#include<malloc.h>
struct treenode
{
unsigned int data;
struct treenode *left;
struct treenode *right;
};
struct treenode *treeptr, *sourcenode, *quesnode, *quesleftnode, *quesrightnode, *root = NULL;
struct node *treeptr insert_node(unsigned int treedata)
{
treeptr= (struct node*)(malloc(sizeof(treenode)));
treeptr->data = nodevalue;
treeptr->left = NULL;
treeptr->right = NULL;
return treeptr;
}
printnodesdistancek(struct treenode* quesnode, unsigned char reqdist)
{
unsigned char curdist=0;
do
{
if(quesnode == null)
return;
quesleftnode = quesnode->left;
if(curdist == reqdist)
{
printf("%d",quesleftnode->data);
}
else
{
quesnode= quesnode->left;
}
quesrightnode = quesnode->right;
if(curdist == reqdist)
{
printf("%d",quesrightnode->data);
}
else
{
quesnode = quesnode->right;
}
}while(quesnode!=NULL);
//main function
void main(void)
{
//create tree
*root = insert_node(1);
root->left=insert_node(-1);
root->right=insert_node(2);
root->left->left=insert_node(-2);
root->left->right=insert_node(3);
root->right->left=insert_node(-3);
root->right->right=insert_node(4);
sourcenode = root->left;
printnodesdistancek(sourcenode,1);
}
This is an Amazon interview question. Can any one give an algorithm to do this?
There is a binary tree with the following properties:
All of its inner node have the value 'N', and all the leaves have the value 'L'.
Every node either has two children or has no child.
Given its preorder, construct the tree and return the root node.
Since it is guaranteed that each internal node has exactly 2 children, we can simply build the tree recursively using that.
We call our function with the input provided, and it examines the first character it got. If it is a leaf node, it just returns a leaf. If it is an internal node, it just calls itself for the left and right subtrees and returns the tree formed using the node as root and the left and right subtrees as its left and right children.
Code follows (in Python). Note, I am using tuples to represent node, so the tree is a tuple of tuples.
#! /usr/bin/env python
from collections import deque
def build_tree(pre_order):
root=pre_order.popleft()
if root=='L':
return root
else:
return (root,build_tree(pre_order),build_tree(pre_order))
if __name__=='__main__':
print build_tree(deque("NNLLL"))
Edit: Code in Java
import java.util.*;
class Preorder{
public static Node buildTree(List<Character> preorder){
char token=preorder.remove(0);
if (token=='L'){
return new Node(token,null,null);
}
else{
return new Node(token,buildTree(preorder),buildTree(preorder));
}
}
public static void main(String args[]){
List<Character> tokens=new LinkedList<Character>();
String input="NNLLL";
for(int i=0;i<input.length();i++) tokens.add(input.charAt(i));
System.out.println(buildTree(tokens));
}
}
class Node{
char value;
Node left,right;
public Node(char value, Node left, Node right){
this.value=value;
this.left=left;
this.right=right;
}
public String toString(){
if (left==null && right==null){
return "("+value+")";
}
else{
return "("+value+", "+left+", "+right+")";
}
}
}
I can think of a recursive algorithm.
head = new node.
remove first character in preorderString
Invoke f(head, preorderString)
Recursive function f(node, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeLeft, attach to node, invoke f(nodeLeft, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeRight, attach to node, invoke f(nodeRight, s)
I think the key point is to realize that there are three possibilities for the adjacent nodes: NN, NL?, L? (``?'' means either N or L)
NN: the second N is the left child of the first N, but we don't know what the right child of the first N is
NL?: the second N is the left child of the first N, and the right child of the first N is ?
L?: ? is the right child of STACK top
A STACK is used because when we read a node in a preorder sequence, we don't know where its right child is (we do know where its left child is, as long as it has one). A STACK stores this node so that when its right child appears we can pop it up and finish its right link.
NODE * preorder2tree(void)
{
NODE * head = next_node();
NODE * p = head;
NODE * q;
while (1) {
q = next_node();
if (!q)
break;
/* possibilities of adjacent nodes:
* NN, NL?, L?
*/
if (p->val == 'N') {
p->L = q;
if (q->val == 'N') { /* NN */
push(p);
p = q;
} else { /* NL? */
q = next_node();
p->R = q;
p = q;
}
} else { /* L? */
p = pop();
p->R = q;
p = q;
}
}
return head;
}
The code above was tested using some simple cases. Hopefully it's correct.
Here is the java program::
import java.util.*;
class preorder_given_NNNLL
{
static Stack<node> stk = new Stack<node>();
static node root=null;
static class node
{
char value;
node left;
node right;
public node(char value)
{
this.value=value;
this.left=null;
this.right=null;
}
}
public static node stkoper()
{
node posr=null,posn=null,posl=null;
posr=stk.pop();
if(stk.empty())
{
stk.push(posr);
return null;
}
else
posl=stk.pop();
if(stk.empty())
{
stk.push(posl);
stk.push(posr);
return null;
}
else
{
posn=stk.pop();
}
if( posn.value == 'N' && posl.value == 'L' && posr.value == 'L')
{
root = buildtree(posn, posl, posr);
if(stk.empty())
{
return root;
}
else
{
stk.push(root);
root=stkoper();
}
}
else
{
stk.push(posn);
stk.push(posl);
stk.push(posr);
}
return root;
}
public static node buildtree(node posn,node posl,node posr)
{
posn.left=posl;
posn.right=posr;
posn.value='L';
return posn;
}
public static void inorder(node root)
{
if(root!=null)
{
inorder(root.left);
if((root.left == null) && (root.right == null))
System.out.println("L");
else
System.out.println("N");
inorder(root.right);
}
}
public static void main(String args[]){
String input="NNNLLLNLL";
char[] pre = input.toCharArray();
for (int i = 0; i < pre.length; i++)
{
node temp = new node(pre[i]);
stk.push(temp);
root=stkoper();
}
inorder(root);
}
}
The construct function does the actual tree construction. The code snippet is the solution for the GeeksforGeeks question that you mentioned as above.
struct Node*construct(int &index, Node*root, int pre[], int n, char preLN[])
{
Node*nodeptr;
if(index==n)
{
return NULL;
}
if(root==NULL)
{
nodeptr = newNode(pre[index]);
}
if(preLN[index]=='N')
{
index = index+1;
nodeptr->left = construct(index, nodeptr->left, pre,n,preLN);
index = index+1;
nodeptr->right = construct(index, nodeptr->right,pre,n,preLN);
return nodeptr;
}
return nodeptr;
}
struct Node *constructTree(int n, int pre[], char preLN[])
{
int index =0;
Node*root = construct(index,NULL,pre,n,preLN);
return root;
}
Points to Note:
Index has been declared a reference variable so that on returning back to the parent node, the function starts constructing the tree from the overall most recent value of index and not the value of index as possessed by the function when initially executing the call.
Different values of index for right and left subtrees since preorder traversal follows Root, Left ,Right sequence of nodes.
Hope it Helps.