Cracking coding interview(2.5) 查找环形链表的环形起点

copyright:Craking coding interview

109 Cracking the Coding Interview | Data Structures
2.5 Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C

第一种方法:使用Hashtable<Integer, String>或Hashtable<Node, String> 均可,假定Node.data可以唯一标识一个节点,否则的话,应该用第2种Hashtable泛型用法。

第二种方法查看链接:http://article.yeeyan.org/view/9225/173996

import java.util.Hashtable;

class Node{
	int data;
	Node next;
	public Node(int data){
		this.data = data;
		next = null;
	}
}
public class Solution{
	public static Node getLoopNode1(Node head){
		Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		Node p = null;
		for(p=head;p != null;p = p.next){
			if(hash.containsKey(p.data)){
				return p;
			}else{
				hash.put(p.data, "");
			}
		}
		//the list isn't loop list
		//if(p == null)
			return null;
	}
	public static Node getLoopNode2(Node head){
		Node p1 = head, p2 = head;
		//ewhen the start :p1.data == p2.data == head.data,
		//so Usage:do{} while();
		do{
			p1 = p1.next;
			p2 = p2.next.next;	
		}while(p1.data != p2.data && p2 != null && p2.next != null);
		//the list isn't loop list
		if(p2 == null || p2.next == null)
			return null;
		
		
		p1 = head; int i=0;//	
		while(p1.data != p2.data){
			p1 = p1.next;
			p2 = p2.next;
		}
		
		return p1;
	}	
	private static void printLoopNode(Node head){
		Node p = null;
		Hashtable<Integer, String> hash = new Hashtable<Integer, String>();
		for(p = head;p != null;p = p.next){
			if(hash.containsKey(p.data)){
				System.out.print(p.data+" ");
				break;
			}else{
				hash.put(p.data, "");
				System.out.print(p.data+" ");
			}
		}
		System.out.println();
	}	
	public static void main(String[] args){
		Node head = new Node(1);
		head.next = new Node(2);
		head.next.next = new Node(3);
		head.next.next.next = new Node(4);
		head.next.next.next.next = new Node(5);
		//head.next.next.next.next.next = head.next.next;

		Solution.printLoopNode(head);
		Node n = Solution.getLoopNode1(head);
		System.out.println("loop node = " + (n != null ? n.data : null));

	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值