力扣160题(C语言),相交链表

本文介绍了一种在O(n)时间复杂度和O(1)内存条件下,寻找两个单链表相交起始节点的算法。该算法首先计算两链表长度差,再同步遍历长链表和短链表直至找到交点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个程序,找到两个单链表相交的起始节点。

注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 typedef struct ListNode Node;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    if(headA==NULL || headB == NULL )
        return NULL;
    Node* curA = headA;
    Node* curB = headB;
    int lenA = 0,lenB =0;
    while(curA->next)
    {
        lenA++;
        curA = curA->next;
    }
    while(curB->next)
    {
        lenB++;
        curB = curB->next;
    }
int gap = abs(lenA - lenB);
Node* longList = headA,*shortList =headB;
if(lenA < lenB)
{
    longList = headB;
    shortList = headA;
}
while(gap--)
{
    longList = longList->next;
}
while(longList!=shortList)
{
    longList = longList->next;
    shortList = shortList->next;
}
return longList;
}
### 力扣第54的C语言解决方案 力扣第54名为“螺旋矩阵”,其目标是从给定的二维数组中按顺时针方向提取所有元素形成一个一维数组。以下是该问的一种可能的C语言实现: ```c #include <stdio.h> #include <stdlib> int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) { if (matrixSize == 0 || *matrixColSize == 0) { *returnSize = 0; return NULL; } int rows = matrixSize, cols = *matrixColSize; *returnSize = rows * cols; int* result = (int*)malloc(sizeof(int) * (*returnSize)); int top = 0, bottom = rows - 1, left = 0, right = cols - 1; int index = 0; while (top <= bottom && left <= right) { // Traverse from Left to Right for (int col = left; col <= right; col++) { result[index++] = matrix[top][col]; } top++; // Traverse Downwards for (int row = top; row <= bottom; row++) { result[index++] = matrix[row][right]; } right--; if (top <= bottom) { // Traverse from Right to Left for (int col = right; col >= left; col--) { result[index++] = matrix[bottom][col]; } bottom--; } if (left <= right) { // Traverse Upwards for (int row = bottom; row >= top; row--) { result[index++] = matrix[row][left]; } left++; } } return result; } ``` 此代码通过四个边界指针`top`, `bottom`, `left`, 和`right`控制遍历的方向和范围[^1]。 #### 解决方案说明 - **初始化**: 定义了上下左右四条边界的初始值以及返回结果大小。 - **循环逻辑**: 使用while循环不断缩小边界直到无法继续为止。 - **边界调整**: 每次完成一条边上的遍历后,相应地移动边界以准备下一轮遍历。 这种算法的时间复杂度为O(m*n),其中m和n分别是输入矩阵的行数和列数[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值