题目来源:
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
转载请注明出处:http://www.cnblogs.com/chruny/p/4992008.html