本题有两种做法:迭代和递归
本题的本质是:将链表中后k个结点变为前k个,然后将头结点连接到尾节点
迭代
考察知识:
- 边界条件判断
- 链表倒k结点寻找
- Get思想:结环
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode p = head;
int count = 1;
while (p.next != null) {
count++;
p = p.next;
}
k = k % count;
// 成环,寻找 k 结点
p.next = head;
for (int i = 0; i < count - k; i++) {
p = p.next;
}
head = p.next;
p.next = null;
return head;
}
}
递归
暂时没思考