0% found this document useful (0 votes)
17 views

Simple Program Unit 2

The document describes a C program to find and print the middle element of a linked list. It includes the code to insert elements into the list, find the middle node using two pointers, and a sample run. The time complexity is O(N) and space complexity is O(1).

Uploaded by

qwerty keypad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Simple Program Unit 2

The document describes a C program to find and print the middle element of a linked list. It includes the code to insert elements into the list, find the middle node using two pointers, and a sample run. The time complexity is O(N) and space complexity is O(1).

Uploaded by

qwerty keypad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 4

SIMPLE PROGRAM SIDHARTH K

RA2011003010008

CSE A1
Question:
3. Write a program in C to print the element at the middle node of a Linked List.

Approach:
Pointers are used for traversing to find the middle node of the list.

Follow Up Question:
Q) What happens if the number of elements in the list is even?

A) n/2th element is found as the middle element, where “n” is the total number of elements.

Scalability:
User can enter the Size of the list and can define any value.

Code:
#include<stdio.h>

#include<stdlib.h>

//Declaring the structure

struct Node

int data;

struct Node* next;

};
//Function for finding the middle node of the list

void middle(struct Node*head)

struct Node* first=head;

struct Node* last=head;

if(head!=NULL)

while(last!=NULL && last->next!=NULL)

first=first->next;

last=last->next->next;

printf("The middle element is [%d]",first->data);

//Function to insert elements into the list

void push(struct Node **head_ref,int data)

struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

new_node->data = data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

}
int main()

struct Node *head=NULL;

int i,t;

printf("Enter no. of values\n");

scanf("%d",&t);

for(i=t;i>0;i--)

int x;

printf("Enter value to be added to list\n ");

scanf("%d",&x);

push(&head,x);

middle(head);

return 0;

Sample Input and Output:


Dry Run:

Time and Space Complexity:


Time Complexity: O(N)

Space Complexity: O(1)

You might also like