mid element of linked list in single pass

 

#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node *next;

};

 

int f=1;

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;

    while(temp2!=0 && temp2->next!=0)

    {

        temp2=temp2->next->next;

        temp=temp->next;

    }

    printf("\n\nThe element at the middle of the list : %d\n",temp->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