Pages

Showing posts with label xor trick in singly linked list. Show all posts
Showing posts with label xor trick in singly linked list. Show all posts

Sunday, 26 August 2012

Datastructures material page3


 How to traverse singly linked list as like a doubly linkedlist:

That is given a linked list we need traverse till end and then traverse back to start :

note:for all my programs assume head node is available
 
Algorithm:

Every time maintain previous node address and then do XOR operation with current next then move forword do same process till u find current next as null then make previous as null again then traverse
back by using XOR operation of next with previous

Code:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node *next;
}*head=NULL;

//for my appliction i need to insert some elements in to linked list that is why im writing insert //function
void insert(struct node *head,int i)
{
    struct node *temp,*q;
    if(head->next==NULL)
    {
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=i;
    temp->next=NULL;
    head->next=temp;
        printf("inserted when head is null");
  
    }
      
    else
    {
        temp=(struct node *)malloc(sizeof(struct node));
        temp->data=i;
        temp->next=NULL;
        q=head;
        while(q->next!=NULL)
        q=q->next;
        q->next=temp;
        printf("inserted when head is not null");
      
    }
}//end of insert

void display(struct node *head)
{
    struct node *temp;
    temp=head->next;
    while(temp!=NULL)
    {
        printf("%d    ",temp->data);
        temp=temp->next;
        }
    }

void backtrack(struct node *head)
    {
    struct node *temp,*prev,*q;
    temp=head;
    prev=NULL;
    while(temp!=NULL)
    {
        q=temp;
        printf("%d   ",temp->data);
        temp=temp->next;
        q->next=((int)(q->next))^((int)(prev));
        prev=q;
        }
        temp=prev;
        prev=NULL;
        printf("\t");
        while(temp!=head)
        {
            printf("%d  ",temp->data);
            temp->next=((int)(temp->next))^((int)(prev));
            prev=temp;
            temp=temp->next;
            }
              
        printf("%d",temp->data);
     }  


void main()
{
    int i=1,j;
    struct node *head;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
while(i)
{
    printf("\nenter 1 to insert elements ");
    printf(" \n 2 display");
    printf("\n 3 traverse linked list front and back again");
    printf("\n 0 to exit");
    scanf("%d",&i);
  
 switch(i)
 {
    case 1:printf("enter element");
           scanf("%d",&j);
           insert(head,j);
           break;

    case 2:display(head);
           break;
         
    case 3:backtrack(head->next);
           break;

  }
}
}