题解 | #转动链表#

转动链表

http://www.nowcoder.com/practice/afbec6b9d4564c63b2c149ccc01c5678

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
  ListNode* rotateRight(ListNode* head, int k) {
    // corner case
    if (!head || !head->next || k <= 0) return head;

    int len = 1;
    auto tail = head;
    while (tail->next) {
      ++len;
      tail = tail->next;
    }

    k %= len;
    if (!k) return head;

    auto p = head;
    for (int i = 0; i < len - k - 1; ++i)
      p = p->next;

    auto new_head = p->next;
    p->next = nullptr;
    tail->next = head;

    return new_head;
  }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务