#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int getListLength(Node* node)
{
int length = 0;
Node *tail = node;
while (node != NULL)
{
node = node->next;
length++;
}
return length;
}
LinkedList findFirstCommonNode(Node* head1, Node* head2)
{
if (head1 == NULL || head2 == NULL)
{
return NULL;
}
int length1 = getListLength(head1);
int length2 = getListLength(head2);
int n = abs(length1 - length2);
Node* node1 = head1;
Node* node2 = head2;
if (length1 > length2)
{
for (int i = 0; i < n; i++)
{
node1 = node1->next;
}
}
else
{
for (int i = 0; i < n; i++)
{
node2 = node2->next;
}
}
while (node1 != NULL && node2 != NULL)
{
if (node1->data == node2->data)
{
return node1;
}
node1 = node1->next;
node2 = node2->next;
}
return NULL;
}
int main() {
// 创建节点
Node* head = createNode(1);
Node* node2 = createNode(2);
Node* node3 = createNode(3);
Node* node4 = createNode(4);
Node* node5 = createNode(5);
Node* head6 = createNode(1);
Node* node7 = createNode(2);
Node* node8 = createNode(3);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
head6->next = node7;
node7->next = node8;
node8->next = node3;
LinkedList CommonNode = findFirstCommonNode(head, head6);
printf("findFirstCommonNode data: %d \n", CommonNode->data);
//printList(head);
system("pause");
return 0;
}
要找到两个链表的第一个公共节点,可以使用双指针的方法进行处理。下面给出详细的解析和代码实现:
解析:
计算链表长度差: 首先分别遍历两个链表,计算它们的长度差 n。
双指针遍历: 接着,让较长链表的指针先向前移动 n 步,使得两个链表剩余长度相等。
同时遍历找公共节点: 然后,同时遍历两个链表,比较节点是否相等,直到找到第一个公共节点或遍历完成。