package 链表下;
/**
* 旋转链表
*
* @author buder_cp
*
*/
public class rotateList {
/**
* 获取链表长度
*
* @param head
* @return
*/
public static int lengthOfList(ListNode head) {
ListNode p = head;
int n = 0;
while (p != null) {
p = p.next;
n++;
}
return n;
}
public static ListNode rotateRight(ListNode head, int k) {
ListNode pre = head;
int n = lengthOfList(head);
for (int i = 1; i < n - k; i++) {
pre = pre.next; // pre是前半部分的尾节点
}
ListNode newHead = pre.next;
ListNode last = newHead; // newHead是断开的新的头结点
while (last.next != null) {
last = last.next;
}
pre.next = null; // 开始改变指针,pre是新的尾部节点,指向null
last.next = head; // last是断开的尾部节点,并与前半部分链接起来
return newHead;
}
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
ListNode head = ListNode.arrayToList(array);
head = rotateRight(head, 2);
ListNode.printList(head);
}
}
旋转链表
关注
打赏