if(len == from - 1)
fPre = node1;
if(len == to + 1)
tPos = node1;
node1 = node1.next;
}
//判断给定的值是否合理
if(from > to || from < 1 || to > len)
return head;
//把from-to这部分链表进行反转
//node1指向部分链表的第一个节点
node1 = fPre == null ? head : fPre.next;
Node cur = node1.next;//cur指向当前要处理的节点
node1.next = tPos;//先把第一个节点给反转处理了
Node next = null;
while (cur != tPos) {
next = cur.next;//保存当前节点的下一个节点
cur.next = node1;
node1 = cur;
cur = next;
}
if (fPre != null) {
fPre.next = node1;
return head;
}
return node1;
}
2、环形单链表约瑟夫问题
【题目描述】
####【要求】
输入:一个环形单向链表的头节点 head 和报数 m.
返回:最后生存下来的节点,且这个节点自己组成环形单向链表,其他节点都删除掉。
代码如下
//时间复杂度为O(n*m)的解决方法
public static Node josephusKill(Node head, int m) {
if(head == null || m < 1)
return head;
Node last = head;
//定位到最后一个节点
while (head.next != last) {
head = head.next;
}
System.out.println(head.value);
int count = 0;
while (head.next != head) {
if (++count == m) {
head.next = head.next.next;
count = 0;
} else {
head = head.next;
}
}
return head;
}
这个方法的时间复杂度为 O(n * m)。下面用时间复杂度为方法解决。
方法二:时间复杂度为 O(n)
我们可以给环形链表的节点编号,如果链表的节点数为 n, 则从头节点开始,依次给节点编号,即头节点为 1, 下一个节点为2, 最后一个节点为 n.
我们用 f(n) 表示当环形链表的长度为n时,生存下来的人的编号为 f(n),显然当 n = 1 时,f(n) = 1。假如我们能够找出 f(n) 和 f(n-1) 之间的关系的话,我们我们就