C Questions
C Questions
order)
if (!isEmpty(stack)) {
x = pop(stack);
sort(stack);
insert(x, stack);
}
}
void insert(x, stack)
{
type y;
void sort(stack)
{
type x;
if (!isEmpty(stack)) {
x = pop(stack);
sort(stack);
} else
insert(x, stack);
}
That wouldn't work for:
stack = 132
if (!isEmpty(stack)) { /* stack=132 */
x = pop(stack); /* stack=13 x=2*/
sort(stack); /*stack=31 x=2*/
} else
insert(x, stack);
}
Q.3.)Given a linked list, your are asked to find out the nth last element in
the linked-list. (n would be given as the argument to the function)
Last nth element is ( l - n + 1)th element from the beginning, so having two pointers:
- Two pointers indicates the list->head at first
- First pointer goes to nth node from the beginning
- Both pointers goes simultaneously until first pointer comes to the end of the list
- Now second pointer walks ( l - n ) nodes, head node is also assumed one walk for two pointers.
- Then secod pointer now indicates the last nth element.
Test Cases:
- List is null
- List is empty
- List with length 1 ( get 1 )
- List with length 2 ( get 1, 2 )
- List with length 3 ( get 3, 1, 2 )
- Any value larger than the size of list
if ( NULL == list ) {
fprintf( stderr, "list is null...(getLastNth)\n" );
exit(1);
}
p = list->head;
q = list->head;
for ( counter = 0; p && counter < n - 1; p = p->next, counter++ );
if ( NULL == p ) {
fprintf( stderr, "Index is out boundary...(getLastNth)\n" );
exit(1);
}
while ( p->next ) {
q = q->next;
p = p->next;
}
return q->data;
}
Q) Ugly number is the number whose only prime factors are 2, 3 or 5. By convention, 1 is
included.
533.
Pick up 1000, go 200 km, drop 600, return. Pick up 1000, go 200 km, drop
600, return. Pick up 1000, go 200 km, drop 800. Now you have 2000
bananas at 200 km.
Pick up 1000, go 333 km, drop 334, return. Pick up 1000, go 333 km, drop
667. Now you have 1001 bananas at 533 km.
Pick up 1000, go 467 km, drop 533 banans. You now have 533 bananas in
city B and one banana rotting away at 533 km.