偵測linked list是否有loop

最簡單的方式就是替每一個structure設一個flag,然後一直跑,如果發現flag已經被Set的話,就代表有loop。

如果沒有flag的話呢?

設ptr1、ptr2= head

ptr1一次走兩個,ptr2一次走一個,直到ptr1=ptr2 or ptr1=end of list

如果ptr1=ptr2,代表有loop

This entry was posted in 電腦和網際網路. Bookmark the permalink.

One Response to 偵測linked list是否有loop

  1. Yuan says:

    好赞的算法!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s