[LeetCode] Rotate List

来源:互联网 发布:微信骚扰软件 编辑:程序博客网 时间:2024/06/05 16:26

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.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *rotateRight(ListNode *head, int k) {        if(head == nullptr || k <= 0)   return head;        int len = listLength(head);        k %= len;        if(k == 0)  return head;        ListNode *p = head, *new_head = head, *new_end = head;        for(int i = 0; i < k; i++)            p = p->next;        while(p->next)        {            p = p->next;            new_end = new_end->next;        }        new_head = new_end->next;        new_end->next = nullptr;        p->next = head;        return new_head;    }    int listLength(ListNode *head)    {        int len = 0;        while(head)        {            len++;            head = head->next;        }        return len;    }};



0 0
原创粉丝点击