上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* 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) {
}
};
golang 解法, 执行用时: 28 ms, 内存消耗: 7.2 MB, 提交时间: 2021-08-09 09:45:00
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
h1, h2 := headA, headB
for h1 != h2 {
if h1 != nil {
h1 = h1.Next
} else {
h1 = headB
}
if h2 != nil {
h2 = h2.Next
} else {
h2 = headA
}
}
return h1
}
python3 解法, 执行用时: 176 ms, 内存消耗: 29.6 MB, 提交时间: 2021-05-18 15:52:09
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
h1, h2 = headA, headB
while h1 != h2:
if h1:
h1 = h1.next
else:
h1 = headB
if h2:
h2 = h2.next
else:
h2 = headA
return h1