旋转链表
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
解法1:利用栈找到变换后的第一个节点
/**
* 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) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode l1 = new ListNode(0, head);
ListNode cur = l1.next;
int count = 0;
while (cur != null) {
stack.push(cur);
cur = cur.next;
count++;
}
if(count==0) return head;
// 适用于示例2的情形
int j = k % count;
if (j == 0) return head;
//尾节点
ListNode end = stack.peek();
for (int i = 1; i < j; ++i) {
stack.pop();
}
//变换后的头节点
ListNode p = stack.pop();
//变换后的尾节点
ListNode m = stack.pop();
m.next = null;
end.next = l1.next;
l1.next = p;
return p;
}
}
解法2:循环链表
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
ListNode tail = head;
int count = 1;
//找尾节点
while (tail.next != null) {
tail = tail.next;
count++;
}
tail.next = head;
//找到断开的位置
k = k % count;
for(int i=0;i<count-k;i++){
tail=tail.next;
}
//找到头节点
head=tail.next;
tail.next=null;
return head;
}
}