Intersection of Two Linked Lists

来源:互联网 发布:mac 列出文件路径 命令 编辑:程序博客网 时间:2024/05/17 03:24

Description:

Write a program to find the node at which the intersection of two singly linked lists begins.

问题描述:

写一个函数,返回两条链表交集链表的头结点。

限制:

  • 整条链表中均无环
  • 时间复杂度O(n),空间复杂度O(1)

解法一(迭代)

思路:两次迭代操作,假设有A和B两条链表,对于每个链表每次遍历到末尾就将另一条链表的头结点赋给它。对于A完成(a+c)次遍历后,最多还要进行(b+c)次遍历。对于B完成(b+c)次遍历后,最多还要进行(a+c)次遍历。其中c为两条链表的交集。那么A完成(a+c+b)次遍历和B完成(b+c+a)次遍历,两个结点就相遇了(返回交集链表的头结点,任一结点均可)

Code:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null)  return null;        ListNode a = headA;        ListNode b = headB;        while(a != b){            a = a == null ? headB : a.next;            b = b == null ? headA : b.next;        }        return a;    }}
0 0
原创粉丝点击