Last third element from end

 

#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;

};

struct node * head, *temp, *newnode, *temp2;

void create()

{   head=0;

    int choice=1;

    while(choice==1)

    {

       newnode=(struct node*)malloc(sizeof(struct node));

       newnode->next=0;

       printf("enter data : ");

       scanf("%d",&newnode->data);

       if(head==0)

       {

           head=newnode;

           temp=newnode;

       }

       else

        {

            temp->next=newnode;

            temp=newnode;

        }

        printf("Want another node: ");

        scanf("%d",&choice);

    }

 

}

void listprint()

{

    temp = head;

    while(temp!=0)

    {

        printf("%d ",temp->data);

        temp=temp->next;

    }

}

int main()

{

    printf("Create the list : \n");

    create();

    printf("The list is : \n");

    listprint();

    temp=head,temp2=head;

    if(head==0 || head->next==0 || head->next->next==0)

    printf("\n\nLast third element not present\n\n");

    else

    {

        //temp will be pointing to last position,

        //temp2 at last third position;

        temp=head;

        int i=1,pos=3;

        while(i<pos)

        {temp=temp->next;i++;}

        temp2=head;

        while(temp->next!=0)

        {

            temp=temp->next;

            temp2=temp2->next;

        }

printf("\n\nThe element at the last third position will be : %d\n",   temp2->data);

    }

}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree