Rotate List

来源:互联网 发布:奇妙pk10软件免费版 编辑:程序博客网 时间:2024/05/17 09:33

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL andk = 2,
return 4->5->1->2->3->NULL.

题意:将链表末尾的K个数字移到链表首

思路:

1.首先链表长度为n,由于k可能大于n,所以k = k % n;

2.找出需要断开的节点,通过首尾指针之间的间隔(尾指针—头指针  = k)遍历一遍链表即可找出,当尾指针到尾部,头指针就是我们新链表的头部

(一定要记得断开,node.next = null)

3.将原链表的尾部与原链表的头部相连

代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public static ListNode rotate(ListNode head, int n){if(n == 0)return head;ListNode frontNode = head, rearNode = head;int front = 1,rear = 1;while(rearNode != null){if(rear - front != n){rearNode = rearNode.next;rear++;}else{frontNode = frontNode.next;rearNode = rearNode.next;front++;rear++;}}ListNode head1 = frontNode, p = head1;while(p.next != null){p = p.next;}p.next = head;//断开原来的连接while(head.next != head1)head = head.next;head.next = null;return head1;}public static ListNode rotateRight(ListNode head, int n) {if(head == null || head.next == null)return head;int length = 0;ListNode tmp = head;while(tmp != null){length++;tmp = tmp.next;}n = n % length;head = rotate(head, n);return head;    }}


 

0 0
原创粉丝点击