Leetcode 61 Rotate List

链表很多题目还是应用穿针引线的方法。

这道题有两个关键之处:

1.要把tail->next = head

2.找到倒数 k % len + 1的节点,从而能访问到倒数k%len的节点。

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL) {
            return NULL;
        }
        
        ListNode* tail = head;
        int len = 1;
        while(tail->next) {
            ++len;
            tail = tail->next;
        }
        
        tail->next = head;
        
        int remind = len - k%len;
        
        while(remind) {
            tail = tail->next;
            --remind;
        }
        
        ListNode* retHead = tail->next;
        tail->next =  NULL;
        return retHead;
    }
};

 

posted @ 2018-09-04 23:02  ly-bnu  阅读(62)  评论(0)    收藏  举报