


Python program to get the middle element of a linked list, completed in a single iteration
Linked lists are used to store data in discrete memory locations. Nodes containing data items are linked using pointers. Each node consists of two fields. The first field is used to store the data and the second field contains the link to the next node.
Brute force cracking technology
To find the middle element of the linked list, the brute force technique is to find the length of the linked list by iterating through the entire linked list until NULL is encountered, then dividing the length by 2 to get the middle element of the linked list's index. After getting the index of the intermediate element, iterate the linked list again from the beginning and stop when the required index is reached. The data item at this index gives the intermediate element.
Take a variable named "temp" to point to HEAD and initialize "len" to 0
Use temp to iterate through the linked list until NULL is reached, and increment "len" by 1 at each node.
After obtaining the length of the linked list, initialize temp to HEAD again. Iterate through the linked list until len//2.
Using slow and fast pointers (single iteration)
We will use two pointers to traverse the linked list. One is called "slow pointer" and the other is called "fast pointer".
The fast pointer moves twice as fast as the slow pointer.
When the fast pointer reaches the end of the linked list, the slow pointer will be at the middle node.
Therefore, we can directly print the contents of the intermediate nodes.
Example
Consider the following list of links. The middle element is 3.

The fast pointer has reached the last node in the linked list, and the slow pointer now points to node 3. Therefore, 3 is the middle element of the given linked list. Now, consider 6 nodes.

Example
The fast pointer has reached NULL, and the slow pointer points to the 4th node. Therefore, the middle element is 4.
algorithm
Make "slow" and "fast" point to the HEAD of the linked list.
Increase the fast pointer by 2 and the slow pointer by 1 until the fast pointer and fast.next are not equal to NULL
Print the value at the slow pointer.
The time complexity is O(n).
class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def insert_at_the_beginning(self, newVal): newNode = Node(newVal) newNode.next = self.head self.head = newNode def print_middle_element(self): slow=self.head fast=self.head while fast is not None and fast.next is not None: slow=slow.next #slow pointer moves one node fast=fast.next.next #fast pointer moves two nodes print("\n\nthe middle element is ",slow.val) def Print_the_LL(self): temp = self.head if(temp != None): print("The linked list elements are:", end=" ") while (temp != None): print(temp.val, end=" ") temp = temp.next else: print("The list is empty.") newList = LinkedList() newList.insert_at_the_beginning(5) newList.insert_at_the_beginning(4) newList.insert_at_the_beginning(3) newList.insert_at_the_beginning(2) newList.insert_at_the_beginning(1) newList.Print_the_LL() newList.print_middle_element()
Output
The linked list elements are: 1 2 3 4 5 the middle element is 3
The above is the detailed content of Python program to get the middle element of a linked list, completed in a single iteration. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using Notepad++ to run a Python program requires the following steps: 1. Install the Python plug-in; 2. Create a Python file; 3. Set the run options; 4. Run the program.

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

PyCharm is a powerful Python integrated development environment that provides a wealth of functions and tools to help developers improve efficiency. Among them, PyInstaller is a commonly used tool that can package Python code into an executable file (EXE format) to facilitate running on machines without a Python environment. In this article, we will introduce how to use PyInstaller in PyCharm to package Python code into EXE format, and provide specific

Llama3 is here! Just now, Meta’s official website was updated and the official announced Llama 38 billion and 70 billion parameter versions. And it is an open source SOTA after its launch: Meta official data shows that the Llama38B and 70B versions surpass all opponents in their respective parameter scales. The 8B model outperforms Gemma7B and Mistral7BInstruct on many benchmarks such as MMLU, GPQA, and HumanEval. The 70B model has surpassed the popular closed-source fried chicken Claude3Sonnet, and has gone back and forth with Google's GeminiPro1.5. As soon as the Huggingface link came out, the open source community became excited again. The sharp-eyed blind students also discovered immediately

Does PyCharm Community Edition support enough plugins? Need specific code examples As the Python language becomes more and more widely used in the field of software development, PyCharm, as a professional Python integrated development environment (IDE), is favored by developers. PyCharm is divided into two versions: professional version and community version. The community version is provided for free, but its plug-in support is limited compared to the professional version. So the question is, does PyCharm Community Edition support enough plug-ins? This article will use specific code examples to

The Python program development process includes the following steps: Requirements analysis: clarify business needs and project goals. Design: Determine architecture and data structures, draw flowcharts or use design patterns. Writing code: Program in Python, following coding conventions and documentation comments. Testing: Writing unit and integration tests, conducting manual testing. Review and Refactor: Review code to find flaws and improve readability. Deploy: Deploy the code to the target environment. Maintenance: Fix bugs, improve functionality, and monitor updates.

What is GIL? GIL is the abbreviation of global interpreter lock, which is an important concept of python interpreter. The GIL ensures that the Python interpreter can only execute one thread at a time. This means that at any time, only one thread can run Python bytecode. Other threads must wait for the GIL to be available before continuing execution. How does GIL work? The GIL is a lock written in C and located in the Python interpreter. When a thread wants to execute Python bytecode, it must first obtain the GIL. If the GIL is already held by another thread, that thread must wait for the GIL to be available before continuing execution. What impact does the GIL have on Python programs? GIL for Python

Flask installation and configuration tutorial: A tool to easily build Python Web applications, specific code examples are required. Introduction: With the increasing popularity of Python, Web development has become one of the necessary skills for Python programmers. To carry out web development in Python, we need to choose a suitable web framework. Among the many Python Web frameworks, Flask is a simple, easy-to-use and flexible framework that is favored by developers. This article will introduce the installation of Flask framework,
