java实现单向循环链表
链表图解带头结点的链表: 不带头结点的链表: 区别
代码的实现 (增减 删除)节点实现: public class node { private int no; public node next; public node(int no) { this.no = no; } public int getNo() { return no; } @Override public String toString() { return "Node [no=" + no + "]"; } } 链表实现: public class linkedList { private node head;//头结点 public linkedList() { } public boolean add( node newhero) {//添加节点 boolean isSuccessful=false; if(head==null){//处理空表 head=newhero; newhero.next=head; isSuccessful=true; }else{//不为空时 node node= head; while(true){ if (node.next==head){ break; } node=node.next; } node.next=newhero; newhero.next=head; isSuccessful=true; } return isSuccessful; } public node delete(int index) {//删除制定节点 node outputNode = null; node node= head; //指向第一个节点 if ((index)==0) {//查到该节点的前一个节点 outputNode = node; head=null; head = node.next;//删除语句 return outputNode; } int location=0;//计时器 while (true){ // if (isEmpty()) {//如果链表为空中断 break; }else if (location==index-1){//查到该节点的前一个节点 outputNode=node.next; node.next=node.next.next;//删除语句 break; } if (node.next==null){ break; } location++;//计时器加加 node=node.next;//节点后移 } return outputNode; } public boolean isEmpty() { return head==null; } public void display() {//遍历整个链表 node node=head; while(node!=null){ System.out.println(node.toString()); if (node.next.getNo()==head.getNo()){ break; } node=node.next; } //1.对象不为空才能执行---->可避免空指针异常 //2.循环里的收尾不是断开的 } 链表的应用 :约瑟夫问题的求解
输入样例: 人数:39 输出样例: 安全位置是:16 31 问题分析:
java参考代码: @Test public void yuecefuTest() { int input =31; LinkedList <Persion> people = new LinkedList <>(); LinkedList <Persion> people2 = new LinkedList <>(); for (int i = 0; i < input ;i++) { people.add( new Persion(i+1)); } int i = 0; for (int j = input*2-2; j >0 ;j--) { if (i==2){ people2.add(people.remove(i)); i=0; } i++; } for (Persion p:people ) { System.out.println(" "+p.toString()); } } LinkedList 源码分析(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |