详细见:leetcode.com/problems/rotate-list
Java Solution: github
package leetcode;
import tools.ListNode辅助.*;
public class P061_RotateList {
public static void main(String[] args) {
ListNode input = tools.ListNode辅助.A_一维生成器(new int[] {1});
ListNode ans = new Solution().rotateRight(input,0);
tools.ListNode辅助.B_打印链表(ans);
}
/*
* 1 ms
* 9.52%
* 一次AC,好爽!!!
*/
static class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null)
return null;
int len = 1;
ListNode cur = head, pre = null, last = head;
while (last.next != null) {
len ++;
last = last.next;
};
k = k % len;
if (k == 0)
return head;
cur = head; pre = head;
for (int i = -1; i != k; i ++)
cur = cur.next;
// System.out.println("cur: " + cur.val);
while (cur != null) {
cur = cur.next;
pre = pre.next;
}
// System.out.println("pre: " + pre.val);
cur = pre.next;
last.next = head;
pre.next = null;
return cur;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/rotate-list
AC 6ms 31.94%
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode sln;
typedef struct ListNode * pln;
struct ListNode {
int val;
struct ListNode *next;
};
pln rotateRight(pln h, int k) {
pln t = h, a = NULL;
int hn = 1;
if (h == NULL) return h;
while (t->next != NULL) {
hn ++;
t = t->next;
}
if (hn == 1) return h;
t->next = h;
k =hn - (k % hn);
t = h;
printf("h val is %d\r\n", h->val);
for (hn = 1; hn < k; hn ++)
t = t->next;
a = t->next;
t->next = NULL;
return a;
}
struct ListNode * convert_int_to_ListNode(int * arr, int n) {
struct ListNode * head = NULL;
struct ListNode * travel = NULL;
struct ListNode * temp = NULL;
int i = 0;
if (n == 0 || n < 0) return NULL;
travel = (struct ListNode *) malloc(sizeof(struct ListNode));
travel->val = *(arr + 0);
travel->next = NULL;
head = travel;
for (i = 1; i < n; i ++) {
temp = (struct ListNode *) malloc(sizeof(struct ListNode));
temp->val = *(arr + i);
temp->next = NULL;
travel->next = temp;
travel = travel->next;
}
return head;
}
int main() {
int arr[] = {0, 1, 2, 3, 4, 5, 6};
pln h = convert_int_to_ListNode(arr, 7);
pln a = rotateRight(h, 8);
pln t = a;
while (t != NULL) {
printf("%d ", t->val);
t = t->next;
}
printf("\r\n");
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/rotate-list
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月13日
@details: Solution: 79ms 10.36%
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, h, k):
"""
:type h: ListNode
:type k: int
:rtype: ListNode
"""
hn, t, a = 1, h, None
if h == None: return h
while t.next != None:
hn += 1
t = t.next
if hn == 1: return h
t.next = h
k = hn - (k % hn)
t = h
for i in range(1, k):
t = t.next
a = t.next
t.next = None
return a