To find the middle node in Singly Linked List:
Create two node pointers: temp and middle .
Initialize temp and middle with head .
Move middle pointer by one.
Move temp pointer by two.
Iterate 3 and 4, until temp becomes NULL .
int middleNode(){
struct node *temp, *middle;
temp = middle = head;
while(temp!=NULL){
if(temp->next==NULL){
break;
}
middle = middle->next;
temp = temp->next->next;
}
return middle->data;
}
View Full Code
#include<stdio.h>
#include<stdlib.h>
void create();
int lengthOfList();
void traverse();
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
int main(){
int opt;
printf("::Single Linked List Operations::\n1.Creation\n2.Length\n3.Traversing\n4.Exit");
do{
printf("\nSelect operation:\n");
scanf("%d",&opt);
switch(opt){
case 1:
create();
break;
case 2:
printf("Middle node in Singly Linked List is %d",middleNode());;
break;
case 3:
traverse();
break;
case 4:
exit(0);
break;
default:
printf("Invalid operation.\n");
}
}while(opt!=4);
return 0;
}
void create(){
int ch;
struct node *newNode,*lastNode;
lastNode=(struct node*)malloc(sizeof(struct node*));
do{
newNode=(struct node*)malloc(sizeof(struct node*));
printf("Enter node value:\n");
scanf("%d",&newNode->data);
if(head==NULL)
head=newNode;
lastNode->next=newNode;
lastNode=newNode;
printf("To continue press 1 otherwise 0:\n");
scanf("%d",&ch);
}while(ch==1);
lastNode->next=NULL;
}
int middleNode(){
struct node *temp, *middle;
temp = middle = head;
while(temp!=NULL){
if(temp->next==NULL){
break;
}
middle = middle->next;
temp = temp->next->next;
}
return middle->data;
}
void traverse(){
struct node *ptr;
if(head==NULL){
printf("List is empty.\n");
}else{
ptr=head;
while(ptr!=NULL){
printf("%d->",ptr->data);
ptr=ptr->next;
}
printf("NULL");
}
}
Related Programs
Create Singly Linked List with N number of nodes and display.
Perform insertion operation on Singly Linked List.
Perform deletion operation on Singly Linked List.
Reverse of Singly Linked List.
Move last node of Singly Linked List to first.
Swap first and last nodes in a Singly Linked List.
Find the length of Singly Linked List.
Find middle node of Singly Linked List