题解 | #旋转链表#

旋转链表

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;
}
全部评论

相关推荐

05-19 19:54
已编辑
杭州电子科技大学 Java
程序员小白条:《备考软考软件设计师》中级很简单的,不需要花很多时间,除非考软高,这简历找找杭州本地中小厂吧,也很难,项目这块还是最好有自己开发的思考,不要网上的亮点搬过来就行,看运气,本地有优势
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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