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; }
简单链表模拟,找到分界链表节点并连接,调整头节点,坑是不断开尾部会成环
打卡截图