Description

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

思路

  • 先遍历一遍链表,记录长度,同时记录最后一个节点
  • 修正k的大小,找到旋转后的头结点,和它的前一个节点
  • 按照题目要求重新链接链表

代码

/**
 * 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) return head;
        if(!head) return NULL;
        
        ListNode *ptr = head, *tail = NULL;
        int len = 0;
        //找出链表的长度
        while(ptr){
            len++;
            tail = ptr;
            ptr = ptr->next;
        }
        
        //修正k的值
        k = k % len;
        if(k== 0) return head;
        
        int step = len - k + 1;
        ListNode *fastPtr = head;
        ptr = head;
        while(step - 1 > 0){
            step--;
            ptr = fastPtr;
            fastPtr = fastPtr->next;
        }
        
        if(fastPtr){
            tail->next = head;
            ptr->next = NULL;
            return fastPtr;
        }
        
        return head;
    }
};
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

3750 0元 50元 限免
3547 9.8元 98元 1折