天天看点

LeetCode OJ - Rotate List

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

.

分析:链表基本操作练习,包括计算长度、定位、last指针健壮处理、拼接处理。其中要切断的长度为 len - k % len,题目意思写得感觉不清不楚的

/**
 * 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 || !head->next) return head;
        ListNode *cur, *last;
        
        //长度计算
        int len = 0;
        cur = head;
        last = head;
        while(cur) {
            len++;
            last = cur;
            cur = cur->next;
        }
        ListNode *tail = last;
        
        //定位处理
        int i = 0, num = len - k % len;
        cur = head;
        last = head;
        while(cur && i < num) {
            last = cur;
            cur = cur->next;
            i++;
        }
        if(!last->next) return head;
        
        //连接处理
        ListNode *ret = last->next;
        last->next = NULL;
        
        tail->next = head;
        
        return ret;
    }
};
           

继续阅读