6.9刷题打卡

题目 旋转链表

public ListNode rotateLinkedList (ListNode head, int k) {
    // write code here
    if (head == null) return null;
    ListNode phead = new ListNode(0);
    phead.next = head;
    ListNode t = phead.next;
    int n = 0;
    while (t != null) {
        n++;
        t = t.next;
    }
    k %= n;
    int m = n - k;
    ListNode p = phead;
    t = phead.next;
    while (m-- > 0) {
        p = p.next;
        t = t.next;
    }
    p.next = null;
    ListNode newhead = t;
    while (--k > 0) t = t.next;
    t.next = phead.next;
    phead.next = newhead;
    return phead.next;
}

简单链表模拟,找到分界链表节点并连接,调整头节点,坑是不断开尾部会成环

打卡截图

#和牛牛一起刷题打卡#
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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