Title Description
Enter two linked lists to find their first common node.
Thinking analysis: Will one of the linked list node, deposit into the HashMap, will use ContainsKey () to determine whether there is a common node
Code Listing 1:
<span style= "color: #6600cc;" >import java.util.*;p Ublic class Solution {public ListNode findfirstcommonnode (ListNode pHead1, ListNode pHead2 ) { ListNode p=phead1; ListNode q=phead2; Hashmap<listnode,integer> map=new hashmap<listnode,integer> (); while (p!=null) { map.put (p,null); P=p.next; } while (q!=null) { if (Map.containskey (q)) { return q; } else{ q=q.next; } } return null;} } </span>
Code Listing 2:
<span style= "color: #cc33cc;" >public class Solution {public ListNode Findfirstcommonnode (ListNode pHead1, ListNode pHead2) {ListNode cu Rrent1 = phead1;//List 1 ListNode current2 = phead2;//List 2 if (PHead1 = = NULL | | pHead2 = NULL) RE Turn null; int length1 = GetLength (current1); int length2 = GetLength (Current2); The length difference of the two even tables//if the length of the list 1 is greater than the length of the list 2 if (length1 >= length2) {int len = length1-length2; Go through the list 1, the length of the traverse is the length difference between the two linked lists while (len > 0) {current1 = Current1.next; len--; }}//If the length of the list 2 is greater than the length of the linked list 1 else if (Length1 < length2) {int len = length2-length1; Go through the list 1, the length of the traverse is the length difference between the two linked lists while (len > 0) {current2 = Current2.next; len--; }}//begins to go hand in hand until the first common node is found while (Current1!=current2) {current1=curRent1.next; Current2=current2.next; } return current1; }//To specify the length of the linked list public static int getlength (ListNode phead) {int length = 0; ListNode current = Phead; while (current! = null) {length++; current = Current.next; } return length; }}</span>
The first common node of the two linked lists of the offer (44)