[LeetCode 160]Intersection of Two Linked Lists

题目链接:intersection-of-two-linked-lists

/** * Write a program to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:A:a1 → a2↘c1 → c2 → c3↗B:b1 → b2 → b3begin to intersect at node c1.Notes:If the two linked lists have no intersection at all, return null.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory. * */public class IntersectionOfTwoLinkedLists { public class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}} // 42 / 42 test cases passed.// Status: Accepted// Runtime: 327 ms// Submitted: 3 minutes ago//时间复杂度 O(m+n) 空间复杂度 O(1)//解题思路: //1.先分别遍历统计两个链表的节点数。 //2.然后再次遍历,这次让节点数较大的那个链表先走|两节点数值之差|步 //3.最后同时遍历,,判断节点是否相等public ListNode getIntersectionNode(ListNode headA, ListNode headB) {int numA = 0;//A链表的节点数int numB = 0;//B链表的节点数ListNode curA = headA;ListNode curB = headB;while (curA != null) {numA++;curA = curA.next;}while (curB != null) {numB++;curB = curB.next;}curA = headA;curB = headB;while(numA < numB) {curB = curB.next;numB –;}while(numA > numB) {curA = curA.next;numA –;}while(curA != curB) {curA = curA.next;curB = curB.next;}return curA;}public static void main(String[] args) {// TODO Auto-generated method stub}}

重新开始吧!下次我会吸取教训,不让自己犯同样的错误的;

[LeetCode 160]Intersection of Two Linked Lists

相关文章:

你感兴趣的文章:

标签云: