Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
这道题其实思路很简单就是好多细节考虑不到导致编译好几次才成功
尤其是测试的时候考虑K是整个链表长度的整数倍的时候应该怎么处理
看到这道题我的思路首先是利用一次遍历求链表中倒数第K个节点,然后记录倒数第K+1个节点,然后再指针变化就可以了
但是出错!原因是如果K正好是head,这时候K之前的那个节点没法处理
下面附上代码:
public ListNode rotateRight(ListNode head, int k) { if (head == null) { return null; } ListNode temp = head; int len = 0; while(temp!=null){ temp = temp.next; len++; } k = k%len; if (head.next == null || k == 0) { return head; } ListNode pointer = FindKToTail(head, k); if (pointer != null && pointer.next != null) { ListNode pointer1 = pointer.next; ListNode result = pointer1; pointer.next = null; while (pointer1.next != null) { pointer1 = pointer1.next; } pointer1.next = head; return result; } else { return null; } } public ListNode FindKToTail(ListNode head, int k) { if (head == null || k == 0) { return null; } ListNode fast = head; for (int i = 0; i < k; i++) { if (fast.next != null) { fast = fast.next; } else { return head; } } ListNode slow = head; while (fast.next != null) { fast = fast.next; slow = slow.next; } return slow; }
时间: 2024-10-01 07:08:02