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

相關文章
相關標籤/搜索