好久没有看数据结构相关内容,忽然面试官让写判断链表是否有环,竟然写了半天写不出来,汗~
知道自己有多渣,就好好学习吧
接下来开始写判断链表是否有环的方法吧
1.首先定一个结点类Node
package com.example.demo;public class Node{ private T val; private Node next; public Node(T object) { this.val=object; } public void Node(T val) { this.val = val; } public void setVal(T val){ this.val=val; } public T getVal(){ return this.val; } public Node getNext(){ return this.next; } public void setNext(Node node) { this.next = node; } }
2.然后链表类
package com.example.demo;import java.util.List;public class LinkList { private Node root; private Listlist; public LinkList() { } public Node getRoot(){ return this.root; } public List getList() { return list; } public void setList(List list) { this.list = list; } public void setRoot(Node node) { this.root = node; } public boolean isExistRound(Node root){ if(root==null){ return false; } if(root.getNext()==null){ return false; } Node p=root; Node q=root.getNext(); while(q!=null){ if(p==q){ return true; } q=q.getNext(); } return false; }}
3.然后是单元测试
package com.example.demo;import org.junit.Assert;import org.junit.Test;import java.util.ArrayList;import java.util.List;public class LinkListTest { @Test public void should_return_true_when_link_is_round() { String str = "1-2-3-4-5-6"; LinkList roundlinkList = createRoundLinkList(str); Assert.assertEquals(true, roundlinkList.isExistRound(roundlinkList.getRoot())); LinkList notRoundLinkList=createNotRoundLinkList(str); Assert.assertEquals(false, notRoundLinkList.isExistRound(notRoundLinkList.getRoot())); } @Test public void should_return_linked_list_value() { String str = "1-2-3-4-5"; LinkList linkList = createNotRoundLinkList(str); Node node = linkList.getRoot(); while (node != null) { System.out.println(node.getVal() + " "); node = node.getNext(); } } public LinkList createRoundLinkList(String str) { LinkList linkList = createNotRoundLinkList(str); ListnodeList = linkList.getList(); nodeList.get(nodeList.size()-1).setNext(nodeList.get(0)); linkList.setList(nodeList); return linkList; } public LinkList createNotRoundLinkList(String str) { LinkList linkList = new LinkList(); List nodeList = new ArrayList<>(); Object[] objects = str.split("-"); for (int i = 0; i < objects.length; i++) { nodeList.add(new Node<>(objects[i])); } linkList.setRoot(nodeList.get(0)); for (int j = 0; j < nodeList.size() - 1; j++) { nodeList.get(j).setNext(nodeList.get(j + 1)); } linkList.setList(nodeList); return linkList; }}