Rotate List
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 and k = 2,
return 4->5->1->2->3->NULL.
思路一: 确定需要右循环的开头节点和尾部节点,然后和原先的head节点了解起来
java代码:
- public ListNode rotateRight(ListNode head, int n) {
- if(n<=0) return head;
- if(head==null || head.next==null) return head;
- int len = 0;
- ListNode p=head;
- while(p!=null && p.next!=null) {
- len++;
- p=p.next;
- }
- len++;
- ListNode end = p; //尾节点
- n = n%len;
- if(n==0) return head;
- p = head;
- ListNode pre = null;
- n = len - n;
- int i=0;
- while(i<n) {
- i++;
- pre = p;
- p=p.next; //需要循环的头结点
- }
- pre.next = null;
- end.next = head;
- head = p;
- return head;
- }

浙公网安备 33010602011771号