java链表实现约瑟夫环

实现以下java

package com.wzl;

/**
 * @author wuzhilang
 * @Title: Link
 * @ProjectName ranking
 * @Description: java链表实现约瑟夫环
 * @date 2019/4/289:42
 */
class ListNode{
	int data;
	ListNode next;
}
public class Link{
	public static ListNode JosephCycle(ListNode first,int k){

		//第一步:链表构成环
		ListNode tail = first;
		while (tail.next != null){
			tail = tail.next;
		}
		tail.next = first;
		//第二步删除
		ListNode cur = first;
		while(cur.next != cur){//当链表中的节点只剩下最后一个时,跳出循环
			ListNode prev = null;
			for(int i = 0;i<k-1;i++){
				prev = cur;
				cur = cur.next;
			}      // cur就是要删除的点
			prev.next = cur.next;
			cur = null;
			cur = prev.next;  // 让循环继续
		}
		cur.next = null;
		return cur;

	}
	public static void print(ListNode head){
		while(head != null){
			System.out.println(head.data);
			head = head.next;
		}
	}
	public static void main(String[] args) {
		ListNode n1 = new ListNode();
		ListNode n2 = new ListNode();
		ListNode n3 = new ListNode();
		ListNode n4 = new ListNode();
		n1.data = 1;
		n2.data = 2;
		n3.data = 3;
		n4.data = 4;
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		JosephCycle(n1,3);
		print(n1);
	}
}

仓库地址git

相关文章
相关标签/搜索