Rotate List
今天是一道有關(guān)鏈表的題目,來自LeetCode,難度為Medium,Acceptance為22%。
題目如下
Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given1->2->3->4->5andk = 2,
return4->5->1->2->3.
解題思路及代碼見閱讀原文
回復(fù)0000查看更多題目
解題思路
該題的思路較為簡單。
首先,回憶一下刪除倒數(shù)第k個(gè)節(jié)點(diǎn)的題目。用兩個(gè)指針,一個(gè)先走k步,然后一快一慢,直到快指針為null,慢指針指向的節(jié)點(diǎn)即為我們要刪除的節(jié)點(diǎn)。更多細(xì)節(jié)會在后續(xù)的題目中推送。
然后,該題的思路與之類似。即找到倒數(shù)第k個(gè)節(jié)點(diǎn),讓其next指向null。鏈表的最后一個(gè)節(jié)點(diǎn)指向表頭。
需要注意的是k一定是小于鏈表長度的,因此首先應(yīng)該將k對鏈表的長度取模。
下面是代碼
代碼如下
java版
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if(head == null || k <= 0)
return head;
k = k % getLength(head);
if(k == 0)
return head;
ListNode fast = head;
ListNode slow = head;
for(int i = 0; i < k; i++) {
fast = fast.next;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
ListNode result = slow.next;
slow.next = null;
fast.next = head;
return result;
}
private int getLength(ListNode head) {
int length = 0;
while(head != null) {
head = head.next;
length++;
}
return length;
}
}
關(guān)注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學(xué)有所幫助
image