判断链表是否成环

it2026-03-10  4

判断链表是否成环

思路:设定两个指针,一个快,一个慢,如果相遇则成环,记住判定数组是否溢出,即代码while中的内容,p2不为空,且p2的下一个结点也不为空

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode *p1 = head; ListNode *p2 = head; while(p2!=NULL && p2->next!=NULL) { p1 = p1->next; p2 = p2->next->next; if(p1 == p2) return true; } return false; } };
最新回复(0)