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?
I don't see how you could do it without traversing the entire list unless you know the length.
I'm guessing the answer wants one pointer to be traversing one element at a time, while the second pointer moves 2 elements at a time.
This way when the second pointer reaches the end, the first pointer will be at the middle.
In C, using pointers, for completeness. Note that this is based on the "Tortoise and Hare" algorithm used for checking if a linked list contains a cycle.
Our node is defined as the following:
Then our algorithm is thus:
For a list with an even number of nodes this returns the node proceding the actual centre (e.g. in a list of 10 nodes, this will return node 6).
Using C# to find a middle element of the linked list
The below code will help you get the middle element. You need to use two pointers "fast" and "slow". At every step the fast pointer will increment by two and slower will increment by one. When the list will end the slow pointer will be at the middle.
Let us consider the
Node
looks like thisAnd LinkedList has a getter method to provide the head of the linked list
The below method will get the middle element of the list (Without knowing the size of the list)
Example:
If the list is 1-2-3-4-5 the middle element is 3
If the list is 1-2-3-4 the middle element is 3
Using a size variable you can maintain the size of the Linked list.
Then from a client method find the middle of the size of the list:
I dont know if this is better than the two node way, but here also you dont have to traverse through the entire loop.