要找出两个单链表的公共节点,可以使用以下算法:
- 遍历第一个链表,将链表中的每个节点的地址存储在一个哈希表中。
- 遍历第二个链表,对于每个节点,检查它是否在哈希表中存在。
- 如果存在,则该节点就是两个链表的公共节点。
- 如果遍历完第二个链表都没有找到公共节点,则说明两个链表没有公共节点。
#include <stdio.h>
#include <stdlib.h>// 定义链表节点结构
struct ListNode {
int val;
struct ListNode* next;
};// 创建链表节点
struct ListNode* createNode(int val) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}// 找出两个链表的公共节点
struct ListNode* findCommonNode(struct ListNode* head1, struct ListNode* head2) {
// 创建哈希表
int hash[10000] = {0};// 遍历第一个链表,将节点地址存储在哈希表中
struct ListNode* current = head1;
while (current != NULL) {