LeetCode 141. Linked List Cycle

来源:互联网 发布:帝国时代3mac三合一 编辑:程序博客网 时间:2024/06/10 20:08

题目:
Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:
判断一个链表中是否有循环,运用快慢指针,如果有循环,肯定会相遇

代码:

/** * 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 *slow = head;         ListNode *fast = head;         while(fast != NULL && fast->next != NULL){//用快慢指针方法,如果有循环             fast = fast->next->next;             if(fast == slow){//则一定存在相遇情况                 return true;             }         }         return false;    }};
0 0
原创粉丝点击