[关闭]
@XQF 2018-03-07T22:52:11.000000Z 字数 759 阅读 1392

如何判断两个链表是否相交?寻找相交的第一个节点

数据结构与算法


1.是否相交

这里还是有一点没有理解到,链表相交,。说是链表相交的话尾节点一定是一样的

  1. public boolean isIntersect(ListNode head1,ListNode head2){
  2. if(head1==null||head2==null){
  3. return false;
  4. }
  5. while(head1.next!=null){
  6. head1=head1.next;
  7. }
  8. while(head2.next!=null){
  9. head2=head2.next;
  10. }
  11. if(head1==head2){
  12. return true;
  13. }
  14. return false;
  15. }

2.寻找第一个相交节点

想办法使得遍历两个链表的时候进行同步。首先判断是否相交。然后判断较长的一个链表。截去前面多的不要,因为相交尾节点相同的话,前半部分多的是绝对不会相交的。

  1. public int findFirstIntersect(ListNode head1, ListNode head2) {
  2. if (!isIntersect(head1, head2)) {
  3. return -1;
  4. }
  5. int len1 = length(head1);
  6. int len2 = length(head2);
  7. ListNode p;
  8. ListNode q;
  9. if (len1 > len2) {
  10. p = head1;
  11. q = head2;
  12. } else {
  13. p = head2;
  14. q = head1;
  15. }
  16. int k = Math.abs(len1 - len2);
  17. for (int i = 0; i < k; i++) {
  18. p = p.next;
  19. }
  20. while (p != null) {
  21. if (p == q) {
  22. break;
  23. } else {
  24. p = p.next;
  25. q = q.next;
  26. }
  27. }
  28. return p.val;
  29. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注