您的位置:首页 > 其它

Leetcode: Rotate List

2013-12-17 23:38 183 查看
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 == NULL) {

            return NULL;

        }

        

        // In case k is bigger than the list length

        int list_length = 0;

        ListNode *tail = head;

        while (tail != NULL) {

            ++list_length;

            tail = tail->next;

        }

        k %= list_length;

        if (k == 0) {

            return head;

        }

        

        // Find the original list tail and the rotated list head

        tail = head;

        while (k > 0) {

            tail = tail->next;

            --k;

        }

        ListNode *new_head = head;

        while (tail->next != NULL) {

            tail = tail->next;

            new_head = new_head->next;

        }

        

        tail->next = head;

        head = new_head->next;

        new_head->next = NULL;

        

        return head;

    }

};

==============第二次=================

/**
* 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 (k == 0 || head == NULL) {
return head;
}

int count = 0;
ListNode *cur = head;
ListNode *tail = NULL;
while (cur != NULL) {
tail = cur;
cur = cur->next;
++count;
}

k %= count;
if (k == 0) {
return head;
}

k = count - k;
cur = head;
while (--k > 0) {
cur = cur->next;
}
ListNode *new_head = cur->next;
cur->next = NULL;
tail->next = head;

return new_head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表