欢迎来到入门教程网!

C语言

当前位置:主页 > 软件编程 > C语言 >

剑指offer之判断链表是否包含环

来源:本站原创|时间:2020-01-10|栏目:C语言|点击:

1 问题

判断链表是否包含环

2 思路

2个指针,一个指针走一步,一个指针走2步,如果相遇则有,反之无。

3 代码实现

#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0;
typedef struct node
{
  int value;
  struct node *next;
}Node;
/*
 *判断链表是否有环
 */
int isCircleList(Node *head)
{
  if (head == NULL)
  {
    return false;
  }
  Node *first = NULL;
  Node *second = NULL;
  first = head;
  second = head;
  while (second != NULL && (second->next) != NULL && (second->next->next != NULL))
  {
    first = first->next;
    second = second->next->next;
    if (first == second)
    {
      return true;
    }
  }
  return false;
}
int main()
{
  Node *head = NULL;
  Node *node1 = NULL;
  Node *node2 = NULL;
  Node *node3 = NULL;
  Node *node4 = NULL;
  Node *node5 = NULL;
  Node *node6 = NULL;
  Node *node7 = NULL;
  head = (Node *)malloc(sizeof(Node));
  node1 = (Node *)malloc(sizeof(Node));
  node2 = (Node *)malloc(sizeof(Node));
  node3 = (Node *)malloc(sizeof(Node));
  node4 = (Node *)malloc(sizeof(Node));
  node5 = (Node *)malloc(sizeof(Node));
  node6 = (Node *)malloc(sizeof(Node));
  node7 = (Node *)malloc(sizeof(Node));
  if (head == NULL || node1 == NULL || node2 == NULL || node3 == NULL
    || node4 == NULL || node5 == NULL || node6 == NULL || node7 == NULL)
  {
    printf("malloc fail\n");
    return false;
  }
  //       node7<-node6 <-node5
  //       |       |
  //head->node1->node2->node3->node4
  head->value = 0;
  head->next = node1;
  node1->value = 1;
  node1->next = node2;
  node2->value = 2;
  node2->next = node3;
  node3->value = 3;
  node3->next = node4;
  node4->value = 4;
  node4->next = node5;
  node5->value = 5;
  node5->next = node6;
  node6->value = 6;
  node6->next = node7;
  node7->value = 7;
  node7->next = node2;
  int result = isCircleList(head);
  if (result)
  {
    printf("list have circle\n");
  }
  else
  {
    printf("list do not have circle\n");
  }
  return true;
}

4 运行结果

list have circle

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

上一篇:约瑟夫经典问题扩展成双向约瑟夫问题

栏    目:C语言

下一篇:一元多项式加法运算

本文标题:剑指offer之判断链表是否包含环

本文地址:https://www.xiuzhanwang.com/a1/Cyuyan/423.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有