Find middle element of circular linked list in python
Python program for Find middle element of circular linked list. Here problem description and explanation.
# Python 3 Program # Find middle element in circular linked list class LinkNode : def __init__(self, data) : self.data = data self.next = None class CircularLinkedList : # Class constructor def __init__(self) : self.head = None # Add element at end of circular linked list def insert(self, data) : # Create a new node node = LinkNode(data) if (self.head == None) : self.head = node else : temp = self.head # Find the last node while (temp.next != self.head) : # Visit to next node temp = temp.next # Add node temp.next = node # Connect last node to head node.next = self.head # Display node element of circular linked list def display(self) : if (self.head == None) : print("Empty Linked List") else : temp = self.head # iterate linked list while (temp != None) : # Display node print("", temp.data, end = " ") # Visit to next node temp = temp.next if (temp == self.head) : # Stop iteration return # Find middle node of given circular linked list def findMiddle(self) : if (self.head == None) : print("Empty Linked List") else : if (self.head.next != self.head and self.head.next.next != self.head) : temp = self.head middle = self.head # Find middle node while (temp != None and temp.next != self.head and temp.next.next != self.head) : middle = middle.next temp = temp.next.next print("\n Middle Node is : ", middle.data) else : print("\nLess than three nodes") def main() : cll = CircularLinkedList() # Add linked list nodes cll.insert(1) cll.insert(2) cll.insert(3) cll.insert(4) cll.insert(5) cll.insert(6) cll.insert(7) cll.display() cll.findMiddle() if __name__ == "__main__": main()Output
1 2 3 4 5 6 7 Middle Node is : 4Find middle element of circular linked list in java
Java program for Find middle element of circular linked list. Here more information.
// Java Program // Find middle element in circular linked list class LinkNode { public int data; public LinkNode next; public LinkNode(int data) { this.data = data; this.next = null; } } class CircularLinkedList { public LinkNode head; // Class constructor public CircularLinkedList() { this.head = null; } // Add element at end of circular linked list public void insert(int data) { // Create a new node LinkNode node = new LinkNode(data); if (this.head == null) { this.head = node; } else { LinkNode temp = this.head; // Find the last node while (temp.next != this.head) { // Visit to next node temp = temp.next; } // Add node temp.next = node; } // Connect last node to head node.next = this.head; } // Display node element of circular linked list public void display() { if (this.head == null) { System.out.println("Empty Linked List"); } else { LinkNode temp = this.head; // iterate linked list while (temp != null) { // Display node System.out.print(" " + temp.data); // Visit to next node temp = temp.next; if (temp == this.head) { // Stop iteration return; } } } } // Find middle node of given circular linked list public void findMiddle() { if (this.head == null) { System.out.println("Empty Linked List"); } else { if (this.head.next != this.head && this.head.next.next != this.head) { LinkNode temp = this.head; LinkNode middle = this.head; //Find middle node while (temp != null && temp.next != this.head && temp.next.next != this.head) { middle = middle.next; temp = temp.next.next; } System.out.println("\n Middle Node is : " + middle.data); } else { System.out.println("\nLess than three nodes"); } } } public static void main(String[] args) { CircularLinkedList cll = new CircularLinkedList(); // Add linked list nodes cll.insert(1); cll.insert(2); cll.insert(3); cll.insert(4); cll.insert(5); cll.insert(6); cll.insert(7); cll.display(); cll.findMiddle(); } }Output
1 2 3 4 5 6 7 Middle Node is : 4Q. Program to insert a new node at the middle of the circular linked list.
Explanation
In this program, we create a circular linked list and insert a new node in the middle of the list. If the list is empty, both head and tail will point to new node. If the list is not empty, then we will calculate the size of the list and divide it by 2 to get the mid-point of the list where the new node needs to be inserted.
After inserting the new node in the middle of the list.
Consider the above diagram; the new node needs to be added to the middle of the list. First, we calculate the size which in this case is 4. So, to get the mid-point, we divide it by 2 and store it in a variable count. We will define two nodes current, and temp such that temp will point to head, and current will point to the node previous to temp. We iterate through the list till mid-point is reached by incrementing temp to temp.next then, insert the new node in between current and temp. Current'next node will be new and the new's next node will be temp.
Algorithm
- Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
- Define another class for creating the circular linked list and it has two nodes: head and tail. Variable size stores the size of the list. It has two methods: addInMid() and display() .
- addInMid() will add the node to the middle of the list:
- It first checks whether the head is null (empty list), then it will insert the node as the head.
- Both head and tail will point to the newly added node.
- If the list is not empty, then we calculate size and divide it by 2 to get the mid-point.
- Define node temp that will point to head and current will point to a node previous to temp.
- Iterate through the list until the middle of the list is reached by incrementing temp to temp.next.
- The new node will be inserted after current and before temp such that current will point to the new node and the new node will point to temp.
- display() will show all the nodes present in the list.
- Define a new node 'current' that will point to the head.
- Print current.data till current will points to head again.
- Current will point to the next node in the list in each iteration.
Q. Program to delete a new node from the middle of the circular linked list.
Explanation
In this program, we will create a circular linked list and delete a node from the middle of the list. If the list is empty, display the message "List is empty". If the list is not empty, we will calculate the size of the list and then divide it by 2 to get the mid-point of the list. We maintain two pointers temp and current. Current will point to the previous node of temp. We will iterate through the list until mid-point is reached then the current will point to the middle node. We delete middle node such that current's next will be temp's next node.
Circular linked list after deleting node from middle of the list
Consider the above list. Size of the list is 4. Mid-point of the node is 2. To remove C from the list, we will iterate through the list till mid-point. Now current will point to B and temp will point to C. C will be removed when B will point to D.
Algorithm
- Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
- Define another class for creating the circular linked list and it has two nodes: head and tail. It has a variable size and two methods: deleteMid() and display() .
- deleteMid() will delete the node from the middle of the list:
- It first checks whethe the head is null (empty list) then, it will return from the function as there is no node present in the list.
- If the list is not empty, it will check whether the list has only one node.
- If the list has only one node, it will set both head and tail to null.
- If the list has more than one node then, it will calculate the size of the list. Divide the size by 2 and store it in the variable count.
- Temp will point to head, and current will point to the previous node to temp.
- Iterate the list till current will point middle node of the list.
- Current will point to node next to temp, i.e., removes the node next to current.
- display() will show all the nodes present in the list.
- Define a new node 'current' that will point to the head.
- Print current.data till current will points to head again.
- Current will point to the next node in the list in each iteration.
Circular Linked List
Circular Linked List is little more complicated linked data structure. In the circular linked list we can insert elements anywhere in the list whereas in the array we cannot insert element anywhere in the list because it is in the contiguous memory. In the circular linked list the previous element stores the address of the next element and the last element stores the address of the starting element. The elements points to each other in a circular way which forms a circular chain. The circular linked list has a dynamic size which means the memory can be allocated when it is required.
Application of Circular Linked List
- The real life application where the circular linked list is used is our Personal Computers, where multiple applications are running. All the running applications are kept in a circular linked list and the OS gives a fixed time slot to all for running. The Operating System keeps on iterating over the linked list until all the applications are completed.
- Another example can be Multiplayer games. All the Players are kept in a Circular Linked List and the pointer keeps on moving forward as a player's chance ends.
- Circular Linked List can also be used to create Circular Queue. In a Queue we have to keep two pointers, FRONT and REAR in memory all the time, where as in Circular Linked List, only one pointer is required.
Implementing Circular Linked List
Implementing a circular linked list is very easy and almost similar to linear linked list implementation, with the only difference being that, in circular linked list the last Node will have it's next point to the Head of the List. In Linear linked list the last Node simply holds NULL in it's next pointer.
So this will be oue Node class, as we have already studied in the lesson, it will be used to form the List.
class Node { public: int data; //pointer to the next node node* next; node() { data = 0; next = NULL; } node(int x) { data = x; next = NULL; } }Circular Linked List
Circular Linked List class will be almost same as the Linked List class that we studied in the previous lesson, with a few difference in the implementation of class methods.
class CircularLinkedList { public: node *head; //declaring the functions //function to add Node at front int addAtFront(node *n); //function to check whether Linked list is empty int isEmpty(); //function to add Node at the End of list int addAtEnd(node *n); //function to search a value node* search(int k); //function to delete any Node node* deleteNode(int x); CircularLinkedList() { head = NULL; } }Insertion at the Beginning
Steps to insert a Node at beginning :
- The first Node is the Head for any Linked List.
- When a new Linked List is instantiated, it just has the Head, which is Null.
- Else, the Head holds the pointer to the fisrt Node of the List.
- When we want to add any Node at the front, we must make the head point to it.
- And the Next pointer of the newly added Node, must point to the previous Head, whether it be NULL(in case of new List) or the pointer to the first Node of the List.
- The previous Head Node is now the second Node of Linked List, because the new Node is added at the front.
Insertion at the End
Steps to insert a Node at the end :
- If the Linked List is empty then we simply, add the new Node as the Head of the Linked List.
- If the Linked List is not empty then we find the last node, and make it' next to the new Node, and make the next of the Newly added Node point to the Head of the List.
Searching for an Element in the List
In searhing we do not have to do much, we just need to traverse like we did while getting the last node, in this case we will also compare the data of the Node. If we get the Node with the same data, we will return it, otherwise we will make our pointer point the next Node, and so on.
Deleting a Node from the List
Deleting a node can be done in many ways, like we first search the Node with data which we want to delete and then we delete it. In our approach, we will define a method which will take the data to be deleted as argument, will use the search method to locate it and will then remove the Node from the List.
To remove any Node from the list, we need to do the following :
- If the Node to be deleted is the first node, then simply set the Next pointer of the Head to point to the next element from the Node to be deleted. And update the next pointer of the Last Node as well.
- If the Node is in the middle somewhere, then find the Node before it, and make the Node before it point to the Node next to it.
- If the Node is at the end, then remove it and make the new last node point to the head.
- ← Prev
- Next →