2.6 题目:
给定一个有环链表,实现一个算法返回环路的开头节点
比如 A--B--C--D--E--C
返回C
解法:
遍历链表,把每个节点的hashcode值(地址值)作为key存入hashMap中,若后续判断存在该key,则证明存在环路,返回该结点
- public static <E> Node<E> isCircle(Node<E> head){
- if(head == null || head.next == null)
- return null;
- HashMap map = new HashMap<>();
- Node<E> p = head;
- map.put(p.hashCode(), null);
- while(p.next != null){
- if(map.containsKey(p.next.hashCode())){
- return p.next;
- }
- else{
- map.put(p.next.hashCode(), null);
- }
- p = p.next;
- }
- return null;
- }
测试用例:
- @Test
- public void test_2_6(){
- Node<Integer> head = new Node<>(0);
- createIntegerNode(head, 20);
- printNodeList(head);
- Node<Integer> p = head;
- while(p.getNext()!=null){
- p = p.getNext();
- }
- p.setNext(head);
- System.out.println(LinkedListUtil.isCircle(head));
- }
测试结果:
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
Node [item=0]