160.相交链表

题目描述:

image.png


解:

  1. public class Solution {
  2. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  3. Deque<ListNode> d1 = new ArrayDeque(), d2 = new ArrayDeque();
  4. while (headA != null) {
  5. d1.addLast(headA);
  6. headA = headA.next;
  7. }
  8. while (headB != null) {
  9. d2.addLast(headB);
  10. headB = headB.next;
  11. }
  12. ListNode ans = null;
  13. while (!d1.isEmpty() && !d2.isEmpty() && d1.peekLast().equals(d2.peekLast())) {
  14. ListNode c1 = d1.pollLast(), c2 = d2.pollLast();
  15. ans = c1;
  16. }
  17. return ans;
  18. }
  19. }