public static LinkListNode findtheFirstNode(LinkListNode head1,LinkListNode head2) { Stack<LinkListNode> st1 = new Stack<LinkListNode>(); Stack<LinkListNode> st2 = new Stack<LinkListNode>(); LinkListNode temp; for(temp=head1;temp!=null;temp=temp.next) st1.push(temp); for(temp= head2;temp!=null;temp=temp.next) st2.push(temp); LinkListNode result = null; while(st1.peek() == st2.peek()) { result = st1.pop(); st2.pop(); } return result; }思路二:
public static LinkListNode findFirstSameNode2(LinkListNode head1,LinkListNode head2) { LinkListNode result = null; int countOne = 0; int countTwo = 0; for(LinkListNode p = head1 ; p!=null ;p=p.next) countOne++; for(LinkListNode p = head2 ; p!=null ;p=p.next) countTwo++; LinkListNode pLonghead=head1; LinkListNode pShorthead = head2; int diff = countOne - countTwo; if(countOne < countTwo) { pLonghead = head2; pShorthead = head1; diff =countTwo-countOne ; } for(int i = 0;i<diff ;++i) { pLonghead = pLonghead.next; } while(pLonghead!=null && pShorthead!=null && pLonghead != pShorthead) { pLonghead = pLonghead.next; pShorthead = pShorthead.next; } return pLonghead; }
版权声明:本文为博主原创文章,转载请注明出处。
原文地址:http://blog.csdn.net/u014307117/article/details/47747853