【LeetCode】61. 旋转链表

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

基本思路是每次循环先找到倒数第二节点的位置,然后把头结点的next指向最后一个节点,倒数第二节点的next指向NULL

需要注意的是,实际上K=1和K=链表长度+1时,返回的结果是一致的,需要对K作取余处理

ListNode* Solution::rotateRight(ListNode* head, int k)
{
    ListNode *pnewhead = new ListNode(0);
    ListNode *ptemp;
    ListNode *plength = head;
    unsigned int index = 0;
    unsigned int length = 0;
    unsigned int loop = 0;
    
    if((head == NULL)||(head->next == NULL))
    {
        return head;
    }
    while(plength != NULL)
    {
        plength = plength->next;
        length ++;
    }
    if(k%length == 0)
    {
        loop = length;
    }
    else
    {
        loop = k%length;
    }
    pnewhead->next = head;
    for(index = 0; index < loop; index ++)
    {
        ListNode *plast = pnewhead->next;
        while(plast->next->next != NULL)
        {
            plast = plast->next;
        }
        ptemp = pnewhead->next;
        pnewhead->next = plast->next;
        plast->next->next = ptemp;
        plast->next = NULL;
    }
    return pnewhead->next;
}

猜你喜欢

转载自blog.csdn.net/syc233588377/article/details/85233241