leetcode.61

《leetcode.61》 旋转链表

这道题在leetcode上难度是中等还是比较意外的,做下来难度并不是很大。

思路

找到链表的末结点以及末结点的前驱,根据k的长度调整链表

特殊情况—>解决方法

1.链表为空时—>判断
2.末结点不存在前驱时—>判断
3.k的数字过于大时—>取余

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
/*当k的长度是链表长度的整数倍时,链表恢复原状*/
int getlen(struct ListNode* head)
{
    int c=0;
    while(head!=NULL)
    {
        ++c;
        head=head->next;
    }
    return c;
}
struct ListNode* rotateRight(struct ListNode* head, int k) {
    struct ListNode* p,*q,*r;
    p=head;
    int c=getlen(head);
    if(p==NULL)return NULL;
    if(p->next==NULL)return head;
    k=k%c;
    if(k==0)return head;
    for(int i=0;i<k;++i)
    {
        p=head;
        while(p->next->next!=NULL)
        {
            p=p->next;
        }
        r=p->next;
        q=p;
        q->next=NULL;
        r->next=head;
        head=r;
    }
    return head;
}

有朋友有更好的思路以及方法,欢迎留言讨论。

    原文作者:小气的王二狗
    原文地址: https://www.jianshu.com/p/51adc581f6a2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞