141. 环形链表(C/C++题解含VS可运行源码)

1.力扣C源码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    if (head == NULL) {
        return false;
    }
    else {
        struct ListNode* fast = head;
        struct ListNode* slow = head;
        while (true) {
            if (fast->next == NULL || fast->next->next == NULL) {
                return false;
            }
            else {
                fast = fast->next->next;
                slow = slow->next;
            }
            if (fast == slow) {
                return true;
            }
        }
    }
}

2.题解

方法:快慢指针(很简单)
思想:用快慢双指针遍历链表

  • 快指针一次移动两步,慢指针依次移动一步。
  • 将快慢双指针想象成两个运动员在赛跑,如果链表有环,那么终有一个时刻快慢双指针会重合。
  • 一旦某个节点的next节点出现null,说明不是环形链表。

3.VS可运行源码

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<limits>
#include<algorithm>
#pragma warning(disable:4996)
using namespace std;

//快慢指针
struct ListNode {
    int val;
    struct ListNode *next;
};
int n;
ListNode* List_TailInsert()//尾插法建立带有头节点的链表
{
    ListNode* head = (ListNode*)malloc(sizeof(ListNode));
    ListNode* rear = head;
    printf("输入链表数据:");
    int num;
    for (int i = 0; i < n; i++) {
        scanf("%d", &num);
        ListNode* p = (ListNode*)malloc(sizeof(ListNode));
        p->val = num;
        rear->next = p;
        rear = p;
    }
    rear->next = NULL;
    return head;
}
bool hasCycle(struct ListNode* head) {
    //本题的头节点指的是第一个节点(有数据),和我定义的头节点不一样
    ListNode* head2 = head->next;//所以把我所定义的头节点的下一个节点作为本题的头节点
    //复制到力扣上时把以上这行代码删掉即可,并把下面的head2改为head

    /*if (head2 == NULL) {
        return false;
    }
    else {
        ListNode* fast = head2;
        ListNode* slow = head2;
        while (true) {
            if (fast->next == NULL || fast->next->next == NULL) {
                return false;
            }
            else {
                fast = fast->next->next;
                slow = slow->next;
            }
            if (fast == slow) {
                return true;
            }
        }
    }*/
    //用快慢双指针遍历链表
    //快指针一次移动两步,慢指针依次移动一步。
    //将快慢双指针想象成两个运动员在赛跑,
    //如果链表有环,那么终有一个时刻快慢双指针会重合。
    //一旦某个节点的next节点出现null,说明不是环形链表。
    //简化一下格式
    if (head2 == NULL) return false;
    ListNode* fast = head2;
    ListNode* slow = head2;
    while (true) {
        if (fast->next == NULL || fast->next->next == NULL)return false;
        fast = fast->next->next;
        slow = slow->next;
        if (fast == slow)return true;
    }
}
//这个程序的输出结果与力扣不符,因为自己定义的是单链表(无环),输出永远为0
//重要的是快慢指针思想
int main()
{
    printf("输入要判断链表的长度:");
    scanf("%d", &n);

    ListNode* head = List_TailInsert();
    bool b = hasCycle(head);
    printf("%d", b);

	system("pause");
	return 0;
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐