题解 | #旋转链表#

旋转链表

http://www.nowcoder.com/practice/1ad00d19a5fa4b8dae65610af8bdb0ed

struct ListNode* rotateLinkedList(struct ListNode* head, int k ) 
{
    // write code here
    int count=0;
    struct ListNode*c=head;
    while(c)   // 统计链表长度
    {
        count++;
        c=c->next;
    }
    if(count==0) // 特判长度为零
    {
        return head;
    }
    k%=count;
    if(k==0)    // 特判无需翻转
    {
        return head;
    }
    int i=0;
    struct ListNode*cur=head;
    for(i=0;i<count-k-1;i++)  // 找到反转后的链表头
    {
        cur=cur->next;
    }
    struct ListNode*newhead=cur->next; // 标记新链表头
    cur->next=NULL;
    cur=newhead;
    while(cur->next!=NULL)   // 原链表尾与头链接
    {
        cur=cur->next;
    }
    cur->next=head;
    return newhead;
}
全部评论

相关推荐

10-02 19:29
已编辑
浙江科技大学 运营
职场水母:等春招吧,春招才是双非的主战场,放心吧佬,实习很好,肯定能进大厂的
简历被挂麻了,求建议
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务