链表旋转

题目:

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

示例:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

解题思路:这道题最开始我的想法是记录尾节点的前一个节点,再和头节点交换,但是遍历的时候并不好遍历,所以我换了一种思路:用拆分链表的办法来解决,

分为三步:1、找到正着数第length-k的前一个节点,并记录下一个节点的位置;

                  2、遍历倒数第k个节点到尾节点的所有节点,并链成新的链表;

                  3、将新链表的头作为新的头节点,将原链表的头链到新链表的尾上,返回新链表的头节点。

具体代码如下:

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL)
            return NULL;
        //节点个数
        int length=0;
        ListNode* cur=head;
        while(cur)
        {
            length++;
            cur=cur->next;
        }
        k=k%length;
        if(k==0)
            return head;
        
        int count=length-k;
        ListNode* newhead=new ListNode(0);
        newhead->next=head;
        ListNode* node=newhead;
        //正着走count步
        while(count--)
        {
            node=node->next;
        }
        //拆分链表
        ListNode* tail=node->next;
        ListNode* tailhead=tail;
        node->next=NULL;
        //把倒数第k个节点到尾节点的链起来
        while(tail->next)
        {
            tail=tail->next;
        }
        //把倒数第k个节点之前的,从头节点开始,链到原链表尾节点后面
        tail->next=newhead->next;
        delete newhead;
        return tailhead;
    }
};

猜你喜欢

转载自blog.csdn.net/yam_sunshine/article/details/88768510