利用哈希表判断单链表有环——C语言


前言

判断单链表有环的最佳实现是利用快慢指针法,但是哈希表也可以。

一、头文件

#ifndef HASH_MAP_H
#define HASH_MAP_H
#define _CRT_SECURE_NO_WARNINGS
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define HASHMAP_CAPACITY 10
typedef char* KeyType;
typedef char* ValueType;
//创建链表结点,但是不创建链表结构体,改变头指针时需要用二级指针
typedef int Element;
typedef struct node {
	int data;
	struct node* next;
}Node;
//键值对结点
typedef struct node_s {
	KeyType key;
	struct node_s* next;
}KeyValueNode;
//表结构体
typedef struct {
	//哈希桶
	KeyValueNode* bucket[HASHMAP_CAPACITY];
	//哈希函数需要的种子值
	uint32_t hash_seed;
}HashMap;

//尾插法
void insert_tail(Node** head, Element new_val);
//创建
HashMap* hashmap_create();
//插入
bool hashmap_put(HashMap *map,KeyType key,ValueType val);
//销毁
void hashmap_destroy(HashMap* map);
//利用哈希表判断有无环
bool has_circle(Node* head);

#endif // !HASH_MAP_H


二、基本操作

#include "hash_map.h"
//尾插法
void insert_tail(Node** head, Element new_val) {
	Node* new_node = malloc(sizeof(Node));
	if (new_node == NULL) {
		printf("malloc failed in insert_tail.\n");
		exit(1);
	}
	new_node->data = new_val;
	new_node->next = NULL;
	//如果插入前无节点
	if (*head == NULL) {
		*head = new_node;//插入前为空,把head更新指向new_node
	}
	else {
		//插入前有节点
		Node* last = *head;
		while (last->next) {
			last = last->next;
		}//last指向最后一个值
		last->next = new_node;
	}
}

/* murmur_hash2 */
static uint32_t hash(const void* key, int len, uint32_t seed) {
	const uint32_t m = 0x5bd1e995;
	const int r = 24;
	uint32_t h = seed ^ len;
	const unsigned char* data = (const unsigned char*)key;

	while (len >= 4) {
		uint32_t k = *(uint32_t*)data;
		k *= m;
		k ^= k >> r;
		k *= m;
		h *= m;
		h ^= k;
		data += 4;
		len -= 4;
	}

	switch (len) {
	case 3: h ^= data[2] << 16;
	case 2: h ^= data[1] << 8;
	case 1: h ^= data[0];
		h *= m;
	};

	h ^= h >> 13;
	h *= m;
	h ^= h >> 15;

	return h;
}
//创建
HashMap* hashmap_create() {
	HashMap* map = calloc(1, sizeof(HashMap));
	if (map == NULL) {
		printf("error:calloc failed in hashmap_create.\n");
		exit(1);
	}
	map->hash_seed = time(NULL);
	return map;
}
/*
	该函数会将链表结点的地址作为一个结点key值,存入哈希表当中
	在存入的过程中,如果发现key值重复,说明有环,直接返回true
	如果key值不重复,那就将key结点正常存入哈希表,并且返回false
*/
//插入一个键值对
bool hashmap_put(HashMap* map, KeyType key) {
	//通过哈希函数确定在哪个桶中
	int idx = hash(key, sizeof(KeyType), map->hash_seed) % HASHMAP_CAPACITY;
	//遍历找到的哈希桶,查找key是否重复
	KeyValueNode* curr = map->bucket[idx];
	while (curr) {
		if (key==curr->key) {
			return true;
		}
		curr = curr->next;
	}
	//key不重复就重新插入
	KeyValueNode* new_node = malloc(sizeof(KeyValueNode));
	if (new_node == NULL) {
		printf("Error: malloc failed in hashmap_put.\n");
		exit(1);
	}
	new_node->key = key;
	new_node->next = map->bucket[idx];
	map->bucket[idx] = new_node;
	return false;//表示当前结点还没找到重复结点
}

//利用哈希表判断有无环
bool has_circle(Node* head) {
	HashMap* map = hashmap_create();
	Node* curr = head;
	while (curr) {
		if (hashmap_put(map, curr)) {
			hashmap_destroy(map);
			return true;
		}
		curr = curr->next;
	}
	hashmap_destroy(map);
	return false;
}

//销毁
void hashmap_destroy(HashMap* map) {
	for (size_t i = 0; i < HASHMAP_CAPACITY; i++) {
		KeyValueNode* curr = map->bucket[i];
		while (curr) {
			KeyValueNode* tmp = curr->next;
			free(curr);
			curr = tmp;
		}

	}
	free(map);
}

三、测试源

#include "hash_map.h"
int main(void) {
    Node* head = NULL;
    insert_tail(&head, 1);
    insert_tail(&head, 2);
    insert_tail(&head, 3);
    insert_tail(&head, 4);
    insert_tail(&head, 5);
    
    // 希望构建一个 8->3 的有环链表 希望尾结点指向链表的第三个结点, 第三个结点索引是2
    int count = 0;
    Node* third_node = NULL;
    Node* tail = head;
    while (tail->next != NULL) {
        count++;
        if (count == 3) {
            // tail就指向了第三个结点
            third_node = tail;
        }
        tail = tail->next;
    }	// 循环结束时, tail指向尾结点, third_node指向链表第三个结点
    tail->next = third_node;
    bool ret = has_circle(head);
    if (ret) {
        printf("有环\n");
    }// 有环,返回true
    else {
        printf("无环\n");
    }
    return 0;
}


总结

可以在遍历链表的过程中,将链表的每一个结点存入哈希表,若发现有重复结点被存入哈希表,则确定单链表有环。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值