两个链表的第一个公共结点(Java)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013132035/article/details/82020088

题目:

输入两个链表,找出它们的第一个公共结点。链表结点的定义如下:

struct ListNode{
    int m_nKey;
    ListNode* m_pNext;
}

思路:

第一种解法:蛮力(暴力)法。

第二种解法:借助于栈的先进后出,由于找到两个链表的第一个公共结点,故这个链表在公共结点以后是一个Y字型,故我们将两个链表放入栈中,来找到栈中最后一个相同的结点,即为链表的第一个公共结点。(利用空间来换取时间)

第三种解法:首先遍历两个链表得出两个链表的长度,得出长的链表比短的链表多几个元素,然后长的链表就先走几个元素,然后使其没有遍历的元素和短的链表的元素长度相等。然后再进行遍历,找到第一个公共结点。

代码实现:

ListNode结构

public class ListNode {
	int val;
	ListNode next = null;
	
	ListNode(int val){
		this.val = val;
	}
}

第二种思路代码实现:

public class Main1 {

	public ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2){
		Stack<ListNode> s1 = new Stack<ListNode>();
		Stack<ListNode> s2 = new Stack<ListNode>();
		if(pHead1 == null || pHead2 == null){
			return null;
		}
		while(pHead1!=null){
			s1.push(pHead1);
			pHead1 = pHead1.next;
		}
		while(pHead2!=null){
			s2.push(pHead2);
			pHead2 = pHead2.next;
		}
		ListNode l3 = null;
		while(!s1.isEmpty()){
			ListNode l1 = (ListNode) s1.peek();
			ListNode l2 = (ListNode) s2.peek();
			if(l1 == l2){
				l3 = s1.pop();
				s2.pop();
				continue;
			}
			return l3;
		}
		return null;
	}
}

第三种思路代码实现: 

public class Main {

	public ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2){
		
		if(pHead1 == null || pHead2 == null){
			return null;
		}
		
		int count1 = 0;
		ListNode p1 = pHead1;
		while(p1!=null){
			p1 = p1.next;
			count1 ++;
		}
		
		int count2 = 0;
		ListNode p2 = pHead2;
		while(p2!=null){
			p2 = p2.next;
			count2 ++;
		}
		
		int flag = count1 - count2;
		if(flag > 0){
			while(flag > 0){
				pHead1 = pHead1.next;
				flag --;
			}
			while(pHead1 != pHead2){
				pHead1 = pHead1.next;
				pHead2 = pHead2.next;
			}
			return pHead1;
		}
		
		if(flag < 0){
			while(flag < 0){
				pHead2 = pHead2.next;
				flag ++;
			}
			while(pHead1 != pHead2){
				pHead1 = pHead1.next;
				pHead2 = pHead2.next;
			}
			return pHead1;
		}
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/u013132035/article/details/82020088