Friday, December 14, 2018

Program to reverse a single linked list



//Program to reverse a single linked list
//Assumption: Each item in the list, is added as head in the list
// Improv:- modify such that the element is pushed into the last of list
#include <stdio.h>
#include <stdlib.h>

struct node {
  int data;
  struct node *next;
 
};

void reverse(struct node **head)
{
  struct node *travnode = NULL;
  struct node *prevnode = NULL;
  struct node *nextnode = NULL;
  travnode = *head;
  while(travnode !=NULL)
   
  {
    //Storing the next node is important
    nextnode = travnode->next;
    travnode->next = prevnode;
    prevnode = travnode;
    travnode = nextnode;
  }
 
  *head = prevnode; 
 
   printf("%s\n", "Exiting reverse");
}

static void pushlist(struct node **head, int data)
{
    struct node *currentnode = NULL;
    currentnode = malloc(sizeof(struct node *));
    currentnode->data = data;
    currentnode->next = *head;
    *head = currentnode;
}

void print(struct node *headnode)
{
   
  struct node* travnode = headnode;
  while(travnode!=NULL) {
    printf("%d\t", travnode->data);
    travnode = travnode->next;
   
  }
 
}

int main()
{
 
  int a= 0, b=0, c=0, d=0, e=0;
  struct node *head = NULL;
  printf(" Enter 5 nos :\n");
  scanf( "%d %d %d %d %d", &a, &b, &c, &d, &e);
  pushlist(&head, a);
  pushlist(&head, b);
  pushlist(&head,c);
  pushlist(&head,d);
  pushlist(&head,e);
  print(head);
  reverse (&head);
  print(head);
       
  return 0;
 
}

Sample Output:
Enter 5 nos :
99 88 77 66 55
55  66  77  88  99  Exiting reverse
99  88  77  66  55

Thursday, September 20, 2018

Method to find XOR of two numbers without using XOR operator

I need to find an optimized solution for this interview question. When I mention optimized, it should be truly optimized without over complicating the code.
For the time being, I have written down a not-so optimized code. This will require further testing.


#include <stdio.h>
unsigned int find_xor(unsigned int a,unsigned int b);
int main()
{
    int a, b,c;
    scanf("%d %d", &a,&b);
    c = find_xor((unsigned int)a,(unsigned int)b);
    printf("The xor is %x",c);
    //get(c);
    return 0;
}

unsigned int find_xor(unsigned int a,unsigned int b)
{
 unsigned int c = 0, i=0,d = 0;
 unsigned int a1,b1;
  printf("The a %x b %x \n",a,b);
 while ( (a || b) && (i<32))
 {
     a1 = a &1;
     b1 = b &1;
     printf("The a1 %x b1 %x \n",a1,b1);
     if((a1 != b1)) {
      c = (c<<1)|(1);
      printf("The c %x  \n",c);
     }

     i++;
     a = a>>1;
     b= b>>1;
  }
  //the bits are reverse
   printf("The xor is %x",c);
     while (c) {
         d = (d<<1) |(c & 0x1);
         c = c>>1;
        
     }
 c = d;
 return c;
   
}