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.
比较简单 一次ac beats 77.35%
我的想法是这样 k的值有可能超过链表的长度 以example为例 k=7与k=2的效果是相同的
所以先求一下链表的长度length 然后k%=length
接下来的比较简单 two pointers
f先走k步 然后s出发 在f到达链表结尾时 也就是f=5 s=3
newHead也就是s.next 也就是4
然后断掉s后面 此时
f: 5->null
s:1->2->3
把f和head重新连接 f返回newHead就可以了
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
int length = getLength(head);
k %= length;
if (k == 0) return head;
ListNode f = head;
for (int i=0; i<k; i++) {
f = f.next;
}
ListNode s = head;
while (f.next != null) {
f = f.next;
s = s.next;
}
ListNode newHead = s.next;
s.next = null;
f.next = head;
return newHead;
}
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
head = head.next;
length++;
}
return length;
}
disscuss里面有一个特别的解法 首先找到链表的尾节点 对于example 也就是5 然后tail.next=head
把链表连成了一个环 接下来找到应该断开的地方 也就是length-k=3 也就是3处 然后返回3.next就可以了
因为他之前已经把链表连成了环 所以就不需要再重新连接4->5和1->2->3了
There is no trick for this problem. Some people used slow/fast pointers to find the tail node but I don't see the benefit (in the sense that it doesn't reduce the pointer move op) to do so. So I just used one loop to find the length first.
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
int len=1; // number of nodes
ListNode *newH, *tail;
newH=tail=head;
while(tail->next) // get the number of nodes in the list
{
tail = tail->next;
len++;
}
tail->next = head; // circle the link
if(k %= len)
{
for(auto i=0; i<len-k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)
}
newH = tail->next;
tail->next = NULL;
return newH;
}
};