环形单链表约瑟夫问题

一个环形单链表,从头结点开始向后,指针每移动一个结点,就计数加1,当数到第m个节点时,就把该结点删除,然后继续从下一个节点开始从1计数,循环往复,直到环形单链表中只剩下了一个结点,返回该结点。

思路:当链表为空或者链表只有一个节点或者m<1时,不做处理,直接返回原链表即可。

if (head==null||head.next==head||m<1){
		return head;			
	}

           否则:1:首先遍历整个链表,得到链表的最后一个节点 last , 此时 last.next=head

Node last=head;
while (last.next!=head) {
	last=last.next;			
}

                       2:通过两个指针(last,head)的循环操作,删除遍历到的第m个节点即可。             

int count=0;
while (head.next!=head) {
    if (++count==m) {
		last.next=head.next;//删除节点head
		count=0;
	}
	else{
		last=last.next;		
	}
	head=last.next;
}
return head;
		

整个代码:

public class Node{
		public int value;
		public Node next;
		public Node(int value){
			this.value=value;
		}
		
	}
public Node josephuskill(Node head,int m){
		if (head==null||head.next==head||m<1){
			return head;			
		}
		//首先找到单链表的最后一个节点last,此时last.next=head
		Node last=head;
		while (last.next!=head) {
			last=last.next;			
		}
		//循环删除第m个节点,直到只剩下一个节点为止,此时这个节点的next=他自己
		int count=0;
		while (head.next!=head) {
			if (++count==m) {
				last.next=head.next;//删除节点head
				count=0;
			}
			else{
				last=last.next;		
			}
			head=last.next;
		}
		return head;
		
	}

 

你可能感兴趣的:(环形单链表约瑟夫问题)