題目來源:
https://leetcode.com/problems/rotate-list/
題意分析:
給定一個連結清單和一個整型k,在連結清單從右開始數k處開始旋轉這個連結清單。
題目思路:
首先要确定k是在那個地方,然後開始進行連結清單操作就可以了。要注意的是k有可能比連結清單長度要長,要将k mod 連結清單的長度。
代碼(python):
1 # Definition for singly-linked list.
2 # class ListNode(object):
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution(object):
8 def rotateRight(self, head, k):
9 """
10 :type head: ListNode
11 :type k: int
12 :rtype: ListNode
13 """
14 if k == 0 or head == None:
15 return head
16 tmp = ListNode(0);tmp.next = head
17 t,size = tmp,0
18 while t.next:
19 t = t.next; size += 1
20 t.next = tmp.next
21 for i in range(size - (k % size)):
22 t = t.next
23 head = t.next
24 t.next = None
25 return head
View Code
轉載請注明出處:http://www.cnblogs.com/chruny/p/4992008.html