给定一个链表,判断链表中是否有环。

  • 通过反转链表来做。如果有环的话,链表不变;如果没有环,则链表头变了
/**
 * 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) {
        //反转列表
        if(head == NULL || head->next == NULL)
            return false;

        ListNode *front = NULL, *back = head, *temp;
        while( back -> next != NULL){
            temp = back -> next;
            back -> next = front;
            front = back;
            back = temp;
        }
        back->next = front;

        if(head == back)
            return true;

        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_28038207/article/details/81159668