rotate-list(循环移动链表)

博客围绕链表循环移动问题展开,题目要求将链表向右循环移动 k 个位置(k 为非负)。文中给出三种解决方案,分别是截断重组思路、将链表首尾相接成循环链表以及常规循环思路。

题目描述

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

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

Solution 1(截断重组思路)

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *pre=new ListNode(-1);
        pre->next=head;
        int ListLen=0,pos;
        ListNode *p=head,*q,*r;
        while(p!=NULL)
        {
            ++ListLen;
            p=p->next;
        }
        pos=ListLen-k%ListLen;
        if(pos==ListLen) return head;
        p=head;
        for(int i=0;i<pos-1;++i)
            p=p->next;
        q=pre->next;
        pre->next=p->next;
        r=p;
        while(r->next!=NULL)
            r=r->next;
        r->next=q;
        p->next=NULL;
        return pre->next;
    }
};

Solution 2 (将链表首尾相接成一个循环链表)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*
题目;给定一个链表,将链表旋转到右边的k个位置,其中k是非负的。
例如:
1->2->3->4->5->NULL,为K = 2,
返还4->5->1->2->3->NULL。
*/
/*
分析:先遍历一遍,得出链表长度len,注意k可能会大于len,因此k%=len。
将尾结点next指针指向首节点,形成一个环,接着往后跑len-k步,从这里断开,就是结果
*/
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head==nullptr||k==0)
            return head;
        int len=1;
        ListNode *p=head;
        while(p->next){
            //遍历一遍,求出链表长度
            len++;
            p=p->next;
        }
        k=len-k%len;
         
        p->next=head;//首尾相连
        for(int step=0;step<k;step++){
            p=p->next;//接着往后跑
        }
        head=p->next;//新的首节点
        p->next=nullptr;//断开环
        return head;
    }
};

Solution 3(常规循环思路,一步一步来) 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* lpre(ListNode *phead)
    {
        if(phead==NULL||phead->next==NULL) return phead;
        while(phead->next->next!=NULL)
          phead=phead->next;
        return phead;
    }
    ListNode *rotateRight(ListNode *head, int k) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *pre=new ListNode(-1);
        pre->next=head;
        ListNode *lp=lpre(pre->next);
        for(int i=0;i<k;++k)
        {
            lp->next->next=pre->next;
            pre->next=lp->next;
            lp->next=NULL;
            lp=lpre(pre->next);
        }
        return pre->next;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值