思路:
首先,判断链表是否有环,方法为快慢指针(prear每次走两步,pfront每次走一步),若有环则总有相交的时候;
其次,找出环包含的节点数;
最后,再次遍历链表,找出环的入口结点;
代码如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null||head.next == null||head.next.next == null)
return null;
ListNode first=head;
ListNode second=head;
//以后找链表中间结点用这种方法;
while(second.next!=null&&second.next.next!=null)
{
second=second.next.next;
first=first.next;
if(first == second)
break;
}
if(first!=second)
return null;
//环中的结点数目
int count=1;
while(first.next!=second)
{
first=first.next;
count++;
}
//
first=head;
second=head;
for(int i=1;i<=count;i++)
{
first=first.next;
}
while(first!=second)
{
first=first.next;
second=second.next;
}
return first;
}
}
两个链表的第一个公共节点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 ==null || pHead2 == null){
return null;
}
int length1=0;
int length2=0;
ListNode first = pHead1;
ListNode second = pHead2;
while(first.next != null){
length1++;
first=first.next;
}
while(second.next != null){
length2++;
second=second.next;
}
int diff = length1 - length2;
first = pHead1;
second = pHead2;
if(diff < 0){
diff = length2-length1;
first = pHead2;
second = pHead1;
}
while(diff > 0){
first=first.next;
diff--;
}
while(first.val != second.val && first.next != null){
first=first.next;
second=second.next;
}
if(first.val != second.val){
return null;
}
return first;
}
}