Rotate List

来源:互联网 发布:制作mac安装u盘 编辑:程序博客网 时间:2024/05/29 18:37

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||k==0||!head->next) return head;        int length = 0;          ListNode *ptr = head, *tail = head;          while (ptr) {              length++;              tail = ptr;              ptr = ptr->next;           }          k %= length;         ptr = head;          for (int i = 0; i < length - k - 1; i++)             ptr = ptr-> next;          tail->next = head;          head = ptr->next;          ptr->next = NULL;         return head;        }};


0 0
原创粉丝点击