[LeetCode]160. Intersection of Two Linked Lists
题目描述
思路
本来打算使用翻转链表来做,但是由于链表的结构,和空间复杂度要求,没有成功,之后参考了答案的思路
代码
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = NULL;
while (head) {
ListNode* next = head->next;
head->next = cur;
cur = head;
head = next;
}
return cur;
}
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode *cur1 = headA, *cur2 = headB;
while (cur1 != cur2) {
cur1 = cur1 ? cur1->next : headB;
cur2 = cur2 ? cur2->next : headA;
}
return cur1;
}
void printList(ListNode* head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
};
int main() {
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(2);
ListNode *l3 = new ListNode(3);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
ListNode *l6 = new ListNode(6);
l1->next = l2;
l2->next = l3;
l3->next = l4;
//l6->next = l3;
Solution s;
ListNode* res = s.getIntersectionNode(l6, l5);
s.printList(res);
system("pause");
return 0;
}
本文介绍了解决LeetCode 160题“两个链表的交点”的一种高效算法,通过双指针技巧避免了额外的空间消耗,实现了O(1)的空间复杂度。文章提供了完整的C++代码实现,并附带示例说明。
584

被折叠的 条评论
为什么被折叠?



