码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode 170旋转链表

时间:2017-08-12 01:03:57      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:efi   个数   依次   ota   lis   class   http   null   png   

描述

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

样例

技术分享

思路

计算链表个数len,然后先依次向右移动K个位置然后将后K%len个数字移动到前边来

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), 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=1;
        ListNode* p1=head;
        while(p1->next!=NULL)
        {
            len++;
            p1=p1->next;
        }
        
        k=k%len;
        if(k==0)
        return head;
        
        int step1=len-k-1;
        p1=head;
        while(step1--)
        p1=p1->next;
        
        ListNode* p2=p1->next;
        ListNode* p3=p2;
        while(p3->next!=NULL)
        p3=p3->next;
        
        p3->next=head;
        p1->next=NULL;
        return p2;
    }
};

 

lintcode 170旋转链表

标签:efi   个数   依次   ota   lis   class   http   null   png   

原文地址:http://www.cnblogs.com/li1400802003/p/7348515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!