Leetcode-Rotate List

来源:互联网 发布:centos u盘挂载 编辑:程序博客网 时间:2024/06/02 05:59
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.

题目大意:

给出一个单链表,和一个K值,根据K值往右旋转,例如:

先求出链表的长度length,其实按着倒数第n%length个位置旋转。

AC代码:

public class Solution {//     public ListNode reverseList( ListNode head ){// if( head == null || head.next == null )// return head;// ListNode p = head;// ListNode q = head;// while( q != null ){// ListNode temp = q.next;// q.next = p;// p = q;// q = temp;// }// head.next = null;// head = p;// return head;// }public ListNode rotateRight(ListNode head, int n){if( head == null || head.next == null || n<=0 )return head;ListNode before = head;ListNode after = head;int length = 0;while( before != null ){length++;before = before.next;}before = head;//if( n > length ) return reverseList(head);        if( n%length == 0 ) return head;for( int i=0; i<(n%length); i++ ){after = after.next;}if( after == null ) return head;while( after.next != null ){before = before.next;after = after.next;}ListNode temp = before.next;before.next = null;after.next = head;head = temp;return head;}}


0 0
原创粉丝点击