Get middle element of a linked-list

来源:互联网 发布:戴面具的网络歌手 编辑:程序博客网 时间:2024/06/05 20:06

Suppose there're odd number of elements in a linked-list, how to get the middle element in it? I find a clever way to achieve this on internet. Two pointers point to the linked-list. One is slow pointer and the other is quick pointer. Each time slow pointer moves one step, while the quick pointer moves two steps. When the quick pointer reaches the end of the list, the slow pointer is pointing to the middle of the list.

 

The slow and quick pointers solution can also be used to check whether there's a loop in linked list in O(n) time. If quick pointer reaches slow pointer somewhere sometime, it means there's a loop in linked list.

 

Refering to the mid function followed. It is a solution written in Haskell.

 

原创粉丝点击