Академический Документы
Профессиональный Документы
Культура Документы
Data structures
Queue- Insertion at rear end and deletion at front end. Stack- Insertion and deletion at the top.
void iterative_reverse() { mynode *p, *q, *r; if(head == (mynode *)0) { return; } p = head; q = p->next; p->next = (mynode *)0;
Recursive reverse
mynode* reverse_recurse(mynode *root) { if(root->next!=(mynode *)0) { reverse_recurse(root->next); root->next->next=root; return(root); } else { head=root; } }
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
Copy the data from the next node into this node and delete the next node
Visited flag
Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked list.
Fastest method
p=head; q=head->next;
Write a C program to return the nth node from the end of a linked list.
STEP 1 STEP 2 : 1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 : 1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10
Now, start the second pointer (ptr2) and keep on incrementing it till
So here you have!, the 6th node from the end pointed to by ptr2!
The Y problem Implement a doubly linked list using a single pointer. Hetrogeneous linked list void pointer
Trees
(5*N*N + 4) or (5*N*N - 4)
if(root==NULL)return(NULL);
temp = (mynode *) malloc(sizeof(mynode)); temp->value = root->value;
Can you?
Construct a tree given its inorder and preorder traversal strings. Construct a tree given its inorder and post order traversal strings.
inorder = g d h b e i a f j c preorder = a b d g h e i c f j Scan the preorder left to right using the inorder sequence to separate left and right subtrees. For example, "a" is the root of the tree; "gdhbei" are in the left subtree; "fjc" are in the right subtree. "b" is the next root; "gdh" are in the left subtree; "ei" are in the right subtree. "d" is the next root; "g" is in the left subtree; "h" is in the right subtree.
inorder = g d h b e i a f j c level order = a b c d e f g h i j Tree root is "a"; "gdhbei" are in left subtree; "fjc" are in right subtree.
mynode *closestAncestor(mynode* root, mynode* p, mynode* q) { mynode *l, *r, *tmp; if(root == NULL) { return(NULL); } if(root->left==p || root->right==p || root->left==q || root->right==q) { return(root); } else { l = closestAncestor(root->left, p, q); r = closestAncestor(root->right, p, q); if(l!=NULL && r!=NULL) { return(root); } else { tmp = (l!=NULL) ? l : r; return(tmp); }
} // At the end, prev will have the value of head of the linked list.