Author Bio Show Nora Sandler is a software engineer. After graduating from the University of Chicago, she worked as a penetration tester at Security Innovation, and then as a compiler developer at CrowdStrike, fuelling her interest and research into how computers work under the hood. Sandler writes C Compiler tutorials and has created test programs on her popular blog to make writing a C compiler more accessible. Table of contents Introduction The chapters in red are included in this Early Access PDF. Reviews "It
is refreshing to read a book on compiler design with a focus on implementing a practical real-world language, rather than working through dry academic exercises . . . practical, fun, and exciting to read if you are sick of reading textbooks on the subject." Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. Method 1: Traverse the whole linked list and count the no. of nodes. Now
traverse the list again till count/2 and return the node at count/2. C++
Java
Python3
C#
Javascript
Output 5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3] Time Complexity: O(n) where n is no of nodes in linked list Auxiliary Space: O(1) Method 2: Traverse linked list using two-pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end, the slow pointer will reach the middle of the linked list. Below image shows how printMiddle function works in the code : C++
C
Java
C#
Python3
Javascript
Output 5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3] Time Complexity: O(N), As we are traversing the list only once. Method 3: Initialize the mid element as head and initialize a counter as 0. Traverse the list from the head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only
half of the total length of the list. C++
C
Java
Python3
C#
Javascript
Output 5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3] Time Complexity: O(N), As we are traversing the list
once. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. |