(java实现)单向循环链表
什么是单向循环链表
由于单向循环链表和单向链表的差别真的不大,增添改查原理都相同。因此在这里我们不详细讲解,只提供源码。(如果你还是不理解的话,这里有单向链表的传送门) 源码实现(Java)public class Node<Anytype> { public Anytype data; public Node<Anytype> next; public Node(Anytype data,Node<Anytype> next){ this.data=data; this.next=next; } } ------------------------------------ public class SingleLink<AnyType> { //首元节点 public Node<AnyType> first; //头指针 public Node<AnyType> head; //链表长度 int thesize; //初始化链表 public boolean initlist(){ thesize=0; first=new Node<>(null,null); head=new Node<>(null,first); first.next=head; return true; } //判断链表是否为空 public boolean isEmpty(){ return thesize==0; } //获取节点 public Node<AnyType> getNode(int i){ Node<AnyType> renode=head; for(int j=-2;j<i;j++){ renode=renode.next; } return renode; } //在末尾添加元素 public void add(AnyType a){ Node<AnyType> renode=new Node<>(a,null); getNode(thesize-1).next=renode; renode.next=first.next; thesize++; } //删除i位置节点,并返回删掉的数据 public AnyType remove(int i){ if(i==thesize-1){ AnyType a=getNode(thesize-1).data; getNode(thesize-2).next=first.next; return a; } Node<AnyType> prev=getNode(i-1); AnyType a=prev.next.data; prev.next=prev.next.next; thesize--; return a; } public void remove2(Node<AnyType> n){ } //在i位置插入新节点 public void insert(int i,AnyType a){ Node<AnyType> prev=getNode(i-1); Node<AnyType> renode=new Node<>(a,prev.next); prev.next=renode; thesize++; } //获取i位置节点的数据 public AnyType get(int i){ return getNode(i).data; } //为i位置元素重新赋值 public void set(int i,AnyType a){ getNode(i).data=a; } //返回链表节点个数 public int length(){ return thesize; } //清空链表 public void clear(){ initlist(); } //打印链表 public void print(){ for(int i=0;i<thesize;i++){ System.out.println(getNode(i).data); } } } 单向循环链表的应用----约瑟夫环问题问题来历
思路分析
源码实现(此处的循环单向链表是上面我们实现的-SingleLink)import java.util.Scanner; public class JosephRing { public static void main(String[] args){ int sum=0; int space=0; String s=""; System.out.println("输入环数和间隔"); Scanner sc=new Scanner(System.in); sum=sc.nextInt(); space=sc.nextInt(); SingleLink<Integer> sl=new SingleLink<>(); sl.initlist(); //编号add进链表 for(int i=0;i<sum;i++){ sl.add(i+1); } Node<Integer> n=sl.first; while(n.next!=n){ for(int i=1;i<space;i++){ n=n.next; } int a=n.next.data; n.next=n.next.next; s=s+a+","; } System.out.println(s); } } /* 输入:41 3 输出:3,6,9,12,15,18,21,24,27,30,33,36,39,1,5,10,14,19,23,28,32,37,41,7,13,20,26,34,40,8,17,29,38,11,25,2,22,4,35,16,*/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |