Technical Interview

Tips, questions, answers and puzzles at
www.technical-interview.com

Wednesday, May 2, 2007

Algorithms Questions

1- Write a program to reverse a singly linked list

2- Write a program to delete a node in double linked list

3- Write a program to sort a linked list

4- Write a program to reverse a string

5- Write a program to insert a node a sorted linked list

7 comments:

  1. void rev(char * c){

    if (*c != '\0') rev(c+1);
    cout << *c;
    }

    int main() {
    rev("danny");
    return 0;
    }

    ReplyDelete
  2. in the last algorithm s solution last two steps do not insert a node before another node...it is only possible to insert after a node..do check it...correct me if i m wrong...:)

    ReplyDelete
  3. rev linked list
    reverse(node n){


    if(!n.hasNext()) // is the tail
    return n

    else{
    if(n.isHead())
    n.setNext(null) // make the tail
    return reverse(n.next()).setNext(n)
    }
    }

    ReplyDelete
  4. How abt this?

    void reverseList(struct NODE **root)
    {
    struct NODE *revl = NULL;
    struct NODE *temp = NULL;
    while(*root != NULL)
    {
    temp = *root;
    *root = (*root)->next;
    temp->next = revl;
    revl = temp;
    }
    *root = revl;
    }

    ReplyDelete
  5. void revstr(char* str)
    {
    char temp;
    char * begin=str;
    char * last;
    last= str + strlen(str) -1;

    while (begin < last)
    {
    temp = *begin;
    *begin = *last;
    *last = temp;
    begin++; last--;
    }
    }

    ReplyDelete
  6. node * insert_sorted_list(node *p,int x)
    {
    node * head=p;
    node * q;

    q=(node *) malloc (sizeof(node));
    q->val=x;

    if( x<=head->val)
    {
    q->nxt=head;
    return q;
    }

    while((p->nxt !=NULL) && (p->nxt->val < x))
    p=p->nxt;

    if(p->nxt==NULL)
    {
    p->nxt=q;
    q->nxt=NULL;
    }
    else
    {
    q->nxt=p->nxt;
    p->nxt=q;
    }

    return head;
    }

    ReplyDelete
  7. reverse_linlist()
    {
    NODE *p,*q,*r;

    r=NULL;
    p=head;

    while(p!=NULL)
    {
    q=p->next;
    p->next=r;
    r=p;
    p=q;
    }
    }

    ReplyDelete