快慢指针中的快慢指的是移动的步长,即每次向前移动速度的快慢。
快慢指针的引用:
1.判断单链表是否为循环
2.找到单链表中的中位数
1.Eg:
struct ListNode
{
int val;
struct ListNode *next;
};
typedef struct ListNode list;
struct ListNode *findcircle(struct ListNode *head)//判断是否为循环链表
{
list *fast = head;
list *slow = head;
while (fast&&fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
return 1;
}
}
}
struct ListNode
{
int val;
struct ListNode *next;
};
typedef struct ListNode list;
struct ListNode findmid(struct ListNode *head)//找到中位数
{
list *fast = head;
list *slow = head;
while (fast&&slow)
{
fast = fast->next->next;
slow = slow->next;
if (fast->next == NULL)
{
printf("%d",slow->val);
}
}
}