C語言 快慢指針 判斷是否是環形的鏈表

給定一個有限鏈表,判斷鏈表中是否有環。 所謂的環 不一定是是最後的指向第一個節點, 也可能是指向中間的節點

 

/*
  快慢指針 判斷是否是循環鏈表
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct LinkedList {
  int num;
  struct LinkedList *next;
}LinkedList;

LinkedList *newNode(int num){
  LinkedList *node;
  node = (LinkedList *)malloc(sizeof(LinkedList));
  //  下個節點賦值 設定當前節點的下個節點
  node->num = num;
  node->next = NULL;

  return node;
}

// 創建一個非循環鏈表
LinkedList *initSortStruct(int length){
  LinkedList *current, *node, *headNode;

  for (int i = 1; i <= length; i++){
    if(i == 1){
      headNode = newNode(i);
      node = headNode;
    }else{
      current = newNode(i);
      node->next = current;

      // 重置當前節點
      node = current;
    }
  }

  // 將最後節點的頭節點指向空節點
  current->next = NULL;

  return headNode;
}

// 快慢指針
int quickSlowPoint(LinkedList *X){
  LinkedList *headNode, *Y;
  headNode = X;
  Y = X;

  //  只要指向空節點 那麼 就會退出循環
  while(X != NULL || Y != NULL ){
    if(X->next == NULL){
      return 0;
    }
    X = X->next;
    if(Y->next == NULL || Y->next->next == NULL){
      return 0;
    }
    Y = Y->next->next;

    if(X == Y){
      printf("該鏈表是循環鏈表\n");
      return 1;
    }
  }

  return 0;
}

int main(int argc, char const *argv[]){
  LinkedList *list;

  int length = 44; // 初始化人數 爲 44
  int result;

  list = initSortStruct(length);

  result = quickSlowPoint(list);
  if(result == 0){
    printf("該鏈表是非循環鏈表\n");
  }

  return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章