import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 判断两个链表是否相交
*/
public class LinkedListedCross {
static class Entry {
int value;
Entry next;
public Entry(int value, Entry next) {
this.value = value;
this.next = next;
}
public int hashCode() {
return 37 * value + (next == null ? 0 : next.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Entry))
return false;
Entry entry = (Entry) o;
return value == entry.value && next == entry.next; // 这里用 == 判断next
// 引用,而不是equals
}
public String toString(){
return "{vlaue:"+value+"}";
}
}
static class EntryList {
Entry head, tail;
public EntryList() {
head = tail = new Entry(0, null);
}
public void add(Entry next) {
tail.next = next;
tail = next;
}
public Iterator<Integer> iterator() {
return new Itr();
}
class Itr implements Iterator<Integer> {
Entry p = head.next, pre = head;
@Override
public boolean hasNext() {
return p != null;
}
@Override
public Integer next() {
int val = p.value;
pre = p;
p = p.next;
return val;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
/*
* 判断两个链表是否相交 第一种方法:将其中的一个链表的Entry 存入 Hash,然后查找另一个链表的Entry是否在Hash 值
*/
static void execute(EntryList list1,EntryList list2) {
Set<Entry> set = new HashSet<Entry>();
Entry p = list1.head;
while(p!=null){
set.add(p);
p = p.next;
}
p = list2.head;
while(p!=null){
if(set.contains(p)){
System.out.println("相交 ");
return;
}
p = p.next;
}
}
/*
* 解法三:如果两个链表相交,则最后一个结点一定是它们共有,所以只需判断最后一个结点是否相等即可
* */
static void execute3(EntryList list1,EntryList list2){
Entry last = list1.head;
while(last.next !=null){
last = last.next;
}
Entry p = list2.head;
while(p.next!=null){
p = p.next;
}
System.out.println(p.equals(last)?"相交":"不相交");
}
/*
* 如果两个链表相交,我们将list1 连接到 list2 上,然后从头遍历 list2,看看其是否有环?
* 而判断是否有环也不是太容易,我们就从 list2的头开始遍历,看是否还会回到 list2
* */
static void execute2(EntryList list1,EntryList list2){
Entry p = list1.head,pre = p;
while(p!=null){
pre = p;
p = p.next;
}
pre.next = list2.head;
p = list2.head.next;
while(p!=null && p!=list2.head){
p = p.next;
}
if(p !=null)
System.out.println("相交"+p.toString());
}
public static void main(String args[]) {
EntryList list1 = new EntryList();
list1.add(new Entry(1, null));
list1.add(new Entry(2, null));
list1.add(new Entry(3, null));
EntryList list2 = new EntryList();
list2.add(new Entry(4, null));
list2.add(new Entry(5, null));
list2.add(new Entry(6, null));
Entry both = new Entry(100, null);
list1.add(both);
list2.add(both);
execute3(list1,list2);
}
}
编程之美--判断两个链表是否相交
最新推荐文章于 2015-08-27 21:17:20 发布