旋转链表

来源:互联网 发布:科颜氏淘宝旗舰店 编辑:程序博客网 时间:2024/05/16 02:22
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是新的尾部节点,指向nulllast.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);}}

0 0
原创粉丝点击