Find middle element in doubly linked list
Here given code implementation process.
- C
- C++
- Java
- C#
- Python
- Ruby
- Php
- Node Js
- Swift 4
//C Program
//Find middle element in doubly linked list
#include
#include //for malloc function
//create structure
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
//head and tail pointers
struct Node *head = NULL, *tail = NULL;
//insert Node element of end of linked list
void insert[int value] {
//Create a dynamic Node
struct Node *node = [struct Node *] malloc[sizeof[struct Node]];
if [node == NULL] {
printf["Memory overflow\n"];
} else {
//set data value
node->data = value;
node->next = NULL;
node->prev = NULL;
if [head == NULL] {
head = node;
tail = node;
} else {
node->prev = tail;
tail->next = node;
tail = node;
}
}
}
//display element of Node
void display[] {
struct Node *temp = head;
if [temp == NULL] {
printf["Empty linked list"];
} else {
printf["\n Head to Tail Nodes : \n"];
//Traverse doubly linked list from front to rear
while [temp != NULL] {
//print Node value
printf["%3d", temp->data];
temp = temp->next;
}
printf["\n Tail to Head Nodes : \n"];
temp = tail;
//Traverse doubly linked list from rear to front
while [temp != NULL] {
//print Node value
printf["%3d", temp->data];
temp = temp->prev;
}
}
}
///find mid node
void middle_node[]
{
if[head!=NULL]
{
struct Node*slow=head,*fast=head;
while[fast!=NULL && fast->next != NULL && fast->next->next != NULL]
{
slow = slow->next;
fast = fast->next->next;
}
printf["\n Middle : %d\n",slow->data];
}else
{
//when linked list is empty
printf["Empty linked list"];
}
}
int main[] {
//Insert element of linked list
insert[1];
insert[2];
insert[3];
insert[4];
insert[5];
insert[6];
//Display all node
display[];
middle_node[];
insert[7];
display[];
middle_node[];
printf["\n"];
return 0;
}
Output
Head to Tail Nodes : 1 2 3 4 5 6 Tail to Head Nodes : 6 5 4 3 2 1 Middle : 3 Head to Tail Nodes : 1 2 3 4 5 6 7 Tail to Head Nodes : 7 6 5 4 3 2 1 Middle : 4/*
C++ Program
Find middle element in doubly linked list
*/
#include
using namespace std;
class Node {
public:
int data;
Node *next;
Node *prev;
Node[int value] {
this->data = value;
this->next = NULL;
this->prev = NULL;
}
};
class LinkedList {
public:
Node *head;
Node *tail;
LinkedList[] {
this->head = NULL;
this->tail = NULL;
}
void insert[int value] {
Node *node = new Node[value];
if [node == NULL] {
cout head == NULL] {
this->head = node;
this->tail = node;
} else {
node->prev = this->tail;
this->tail->next = node;
this->tail = node;
}
}
void display[] {
Node *temp = this->head;
if [temp == NULL] {
cout head, *fast = this->head;
while [fast != NULL && fast->next != NULL && fast->next->next != NULL] {
slow = slow->next;
fast = fast->next->next;
}
cout