【多次过】Lintcode 170. 旋转链表

给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数

样例

给出链表1->2->3->4->5->null和k=2

返回4->5->1->2->3->null

解题思路:

    双指针法。

    需要注意旋转操作,需要取k除链表长度的余数。


/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    ListNode * rotateRight(ListNode * head, int k)
    {
        // write your code here
        if(head == NULL)
            return NULL;
        
        int len = get_len(head);
        k = k % len;
        
        ListNode * end = head;
        for(int i=0;i<k;i++)
            end = end->next;
            
        ListNode * start = head;
        while(end->next != NULL)
        {
            start = start->next;
            end = end->next;
        }
        
        end->next = head;
        head = start->next;
        start->next = NULL;
        
        return head;
    }
    
    int get_len(ListNode * head)
    {
        int res = 0;
        while(head)
        {
            res++;
            head = head->next;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/81022942