【LeetCode】Rotate list

Question

Method1

 Using two pointers to make the distance equal k%ListNode.length()//This is got from a loop

/**
 * 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;
        int list_len=0;
        ListNode *pList=head;
        for(;pList;pList=pList->next)
            ++list_len;
        if(list_len<=1)
            return head;

        k=k%list_len;
        if(k==0)
            return head;
        ListNode *pre,*lst;
        pre=lst=head;
        int dis=0;
        while(lst->next){
            if(dis!=k){
                ++dis;
                lst=lst->next;
            }else{
                lst=lst->next;
                pre=pre->next;
            }
        }
        ListNode *tmp=pre->next;
        pre->next=NULL;
        lst->next=head;
        return tmp;
    }
};

Method2

 Using a vector<ListNode*> to make find postion of new head easily.

/**
 * 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) {
        vector<ListNode*> tmp;
        int list_len=0;
        ListNode *pList=head;
        for(;pList;pList=pList->next)
            tmp.push_back(pList);
        list_len=tmp.size();
        if(list_len<=1)
            return head;

        k=k%list_len;
        if(k==0)
            return head;
        ListNode *resHead=tmp[list_len-k];
        tmp[list_len-1]->next=head;
        tmp[list_len-1-k]->next=NULL;

        return resHead;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值