How to find a middle element in a link list without traversing the entire list . ? ...and at the maximum you can use only 2 pointers...how to do ? .... and also the length of list is not given.
标签:
data-structures
相关问题
- C++ a class with an array of structs, without know
- Character.getNumericvalue in char Frequency table
- Quickest method for matching nested XML data again
- QMap but without sorting by key
- Lookup Class In LINQ, What is the underlying data
相关文章
- Is there an existing solution for these particular
- Systematically applying a function to all fields o
- Why can we add null elements to a java LinkedList?
- Is Heap considered an Abstract Data Type?
- Scala variadic functions and Seq
- Word frequency in a large text file
- Solving Josephus with linked lists
- When to use hash tables?
} }
Python code for middle element using two pointer method:
Output: Middle Element is 20
There are two possible answers one for odd and one for even, both having the same algorithm
For odd: One pointer moves one step and second pointer moves two element as a time and when the second elements reach the last element, the element at which the first pointer is, the mid element. Very easy for odd. Try: 1 2 3 4 5
For even: Same, One pointer moves one step and second pointer moves two element as a time and when the second elements cannot jump to next element, the element at which the first pointer is, the mid element. Try: 1 2 3 4
For doubly linked list with given pointers to the head and tail node
we can use both head and tail traversal
Introducing pointer to the middle node may be an option but functions like
insertNode and deleteNode have to modify this pointer
It's stupid to use two pointers "fast" and "slow".Beacause the operator next is used 1.5n times.There is no optimization.
I am adding my solution which will work for both odd and even number of elements scenarios like
1-2-3-4-5 middle element 3
1-2-3-4 middle element 2,3
It is inspired by same fast pointer and slow pointer principle as mentioned in some of the other answers in the post.
} }