Home >Backend Development >PHP Tutorial >A singly linked list with unknown length, how to quickly find the element in the middle?

A singly linked list with unknown length, how to quickly find the element in the middle?

WBOY
WBOYOriginal
2016-07-25 09:08:131302browse
A singly linked list with unknown length, how to quickly find the element in the middle?
  1. // Only ideas
  2. // http://justjavac.iteye.com/blog/1497457
  3. // Set two pointers, p1, p2, and start p1 and p2 at the head of the link.
  4. // p1 takes two steps each time,
  5. // p2 takes one step each time
  6. // When p1 reaches the end of the linked list, the position of p2 is the middle element of the linked list
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn