题目描述:
题目分析:
这道题我一开始竟然使用的是递归去解决(捂脸),确实太丢人了,最后提交的时间和空间的耗费排名可想而知。而后看到了评论区有说所谓的右移,其实就是根据给的数k重新选择第(节点数-k)个结点作为头结点,然后尾结点连接上原来的头结点即可,这句话简直就是一语中的。知道了这种思想,我就去实现它去。结果出来后,时间上果然要比我的原先的代码优秀不少。
代码:
public class RotateRight61 {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node = head;
for (int i = 2; i < 6; i++) {
node.next = new ListNode(i);
node = node.next;
}
ListNode p = head;
while (p!=null){
System.out.print(p.val+"->");
p = p.next;
}
System.out.println();
System.out.println("==========================");
ListNode q = rotateRight(head,6);
while(q!=null){
System.out.print(q.val+"->");
q = q.next;
}
}
public static ListNode rotateRight(ListNode head, int k) {
/**
* 使用递归解决的代码
if (head==null)
return head;
ListNode p = head;
ListNode q = head.next;
int count = 2; //用来记录链中的结点个数
if (q == null)
return head;
while(q.next!=null){
p = q;
q = q.next;
count++;
}
if (k/count>0)
k=k%count;
if (k==0)
return head;
q.next = head;
p.next = null;
return rotateRight(q,--k);
*/
int count = 0; //记录当前链表中的节点数
if (head==null)
return head;
ListNode p = head;
while (p!=null){
p = p.next;
count++;
}
if (k/count>0)
k = k%count; //结合题目规律可知,如果k大于结点总数,则相当于向右挪动了k%count个
if (k!=0){
k=count-k; //结合我们的编程思想,我们需要找到重新为头的节点是第几个节点
}
int i = 0; //用来标记第几个节点是我们重新定义的头结点
ListNode q = head;
while (i!=k){
q = q.next;
i++;
}
ListNode node = q; //现在这个q就是我们的新的头结点了,我们需要额外用一个节点来梳理这个链
while (node.next!=null){
node = node.next;
count--;
}
node.next = head; //遍历到链尾,为它的next绑定上原来的头
while (count!=1){
node = node.next;
count--;
}
node.next = null;
return q;
}
}