C实现 LeetCode->Linked List Cycle 双指针大法)(单链表是否有环)




Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


//判断一个链表是否为 循环链表双指针大法(一快一慢)



C实现 LeetCode->Linked List Cycle 双指针大法)(单链表是否有环)_第1张图片


//
//  LinkedListCycle.c
//  Algorithms
//
//  Created by TTc on 15/6/22.
//  Copyright (c) 2015年 TTc. All rights reserved.
//
/**
 *  Given a linked list, determine if it has a cycle in it.
 
 Follow up:
 Can you solve it without using extra space?
 一块一慢双指针解决。面试常见题了。
 */
#include "LinkedListCycle.h"
#include <stdbool.h>
#include <stdlib.h>
#include "Clist.h"


/********************************************************************/
// LeetCode
/********************************************************************/

struct ListNode {
    int val;
    struct ListNode *next;
};

//判断一个链表是否为 循环链表;  双指针大法(一快一慢)
bool
hasCycle(struct ListNode *head) {
    if(head == NULL) return false;
    
    struct ListNode *iter1 = head->next;
    struct ListNode *iter2 = head;
    
    bool iter2Go = false;
    
    while(iter1 != NULL && iter1->next != NULL){
        if(iter1 == iter2) return true; //单元素
        iter1 = iter1->next;
        //奇数步走慢指针,偶数步骤停止
        if(iter2Go)  iter2=iter2->next;
        iter2Go = !iter2Go;
    }
    
    return false;
}
/********************************************************************/
/********************************************************************/





/********************************************************************/
// List.c 是范性类 单链表
/********************************************************************/

bool
tt_hasCycle(CListElmt *head) {
    if(head == NULL) return false;
    
    CListElmt *iter1 = head->next;
    CListElmt *iter2 = head;
    
    bool iter2Go = false;
    
    while(iter1 != NULL && iter1->next != NULL){
        if(iter1 == iter2) return true;//单元素
        //非单元素
        iter1 = iter1->next;
        //printf("iter1.data=======%d\n", *(int *)iter1->data);
        //奇数步走慢指针,偶数步骤停止
        if(iter2Go){
            iter2=iter2->next;
            //printf("iter2.data=======%d\n", *(int *)iter2->data);
        }
        iter2Go = !iter2Go;
    }
    
    return false;
}

void
test_tt_hasCycle(){
    CList l1;
    clist_init(&l1, free);
    int *data ;
    int array[15] = {100,200,300,400,500,600,700,800,900,1000};
    for (int i = 0; i< 5; i++) {
        if ((data = (int *)malloc(sizeof(int))) == NULL)
            return ;
        *data = array[i];
        if (clist_ins_next(&l1, clist_head(&l1), data) != 0)  //逐个插入元素
            return;
    }
    printf("clist.size===>%d\n",clist_size(&l1));
    cprint_list(&l1);
    bool result = tt_hasCycle(clist_head(&l1));
    printf("result===%d\n",result);
}









你可能感兴趣的:(C实现 LeetCode->Linked List Cycle 双指针大法)(单链表是否有环))