141. 环形链表(C/C++题解含VS可运行源码)
1.力扣C源码
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;
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;
}
}
int main()
{
printf("输入要判断链表的长度:");
scanf("%d", &n);
ListNode* head = List_TailInsert();
bool b = hasCycle(head);
printf("%d", b);
system("pause");
return 0;
}
|