Sunday, August 31, 2014

Rotate List

Problem

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Idea

  • k有可能超过链表的长度,所以先扫一遍得到链表的长度len,然后rotate的实际值是k%len
  • 还是构造一个新的list, 先在旧list中找到新list的第一个node (pivotNode)
  • 然后把从pivotNode 到 最后的所有节点挪到新list里
  • 再把旧list中head到pivotNode的所有节点挪到新List里

  • Solution


    No comments:

    Post a Comment