剑指offer面试题45 圆圈中最后剩下的数字(java实现)

来源:互联网 发布:天津seo点击工具 编辑:程序博客网 时间:2024/05/16 08:25

算法思想:创建一个具有n个节点的环形链表,然后每次在这个链表中删除第m个节点,详细思路可以看看注释

public class Solution {/** * 环形链表的节点类 */class ListNode {public int value;public ListNode next = null;public ListNode(int value) {this.value = value;}}public int LastRemaining_Solution(int n, int m) {if (n <= 0 || m <= 0){return -1;}//创建循环链表ListNode head = new ListNode(0);ListNode pre = head;ListNode current = null;for (int i = 1; i< n; i++) {current = new ListNode(i);pre.next = current;pre = current;}//形成环pre.next = head;//只要环中个数大于1,就继续删while (n > 1) {pre = current = head;int index = 0;//首先需要定位到第m个数字while (index < m - 1) {pre = current;current = current.next;index++;}//找到当前需要删除节点的下一个节点ListNode follow = current.next;//改变指向,进行删除操作pre.next = follow;//圈中数字个数少1n--;//将刚删除节点的下一个元素设置为链表的头元素head = follow;}return head.value;}


阅读全文
0 0
原创粉丝点击