做烧烤的网站,网站策划方案,汽车之家网页版地址,如果在浏览器上做一网站广告大约需要多少钱前言 题目#xff1a; 160. 相交链表 文档#xff1a; 代码随想录——链表相交 编程语言#xff1a; C 解题状态#xff1a; 没思路… 思路
依旧是双指针法#xff0c;很巧妙的方法#xff0c;有点想不出来。
代码
先将两个链表末端对齐#xff0c;然后两个指针齐头并…前言 题目 160. 相交链表 文档 代码随想录——链表相交 编程语言 C 解题状态 没思路… 思路
依旧是双指针法很巧妙的方法有点想不出来。
代码
先将两个链表末端对齐然后两个指针齐头并进容易判断出是否相交。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode* curA headA;ListNode* curB headB;int lenA 0;int lenB 0;while (curA) {lenA;curA curA - next;}while (curB) {lenB;curB curB - next;}curA headA;curB headB;if (lenB lenA) {swap(lenA, lenB);swap(curA, curB);}int gap lenA - lenB;while (gap--) {curA curA - next;}while (curA) {if (curA curB) {return curA;}curA curA - next;curB curB - next;}return NULL;}
};时间复杂度 O ( m n ) O(m n) O(mn)空间复杂度 O ( 1 ) O(1) O(1)