Given a list, rotate the list to the right by k places, where k is non-negative
Example:
Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
这道题是我做的比较满意的,因为用到了经验,说一下我自己的解法:
大众思路:先确定链表长度,然后找出旋转位置,接着重新遍历链表在指定位置断链,然后遍历至结尾链接原链表开头
可以看出时间复杂度为Ω(2N)(暂且这么写),受环状链表启发有如下解法:
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return head;
ListNode first = head;
int length = 1;
while(first.next != null){
length ++;
first = first.next;
}
first.next = head;//链接头尾链表
k = k % length;//k有可能大于length
int index = length - k;
int i = 0;//指针确定断环位置
while(i < index){
first = first.next;
i++;
}
ListNode result = first.next;//新链表头部
first.next = null;//断环
return result;
}
其实思路与上面相同,只不过将最后一步操作放在了中间(将新链表尾部链接原链表头部)
但是略微减少了运行时间,而且简化了代码,辅助变量也减少。