Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
Given this linked list:
1->2->3->4->5
For k = 2, you should return:
2->1->4->3->5
For k = 3, you should return:
3->2->1->4->5
链表题翻转的加强版,思路比较简单,可以先特判一下K=0和K=1的情况。然后每次都找到需要翻转的那一段链表,对下一个节点进行存储,然后将这段链表单独拿出,在必要的位置置null以保证算法能正常的结束。翻转还是使用头插法来进行。在头插的时候记得在最开始赋null以保证最终翻转后的末尾是null,否则可能会产生环。
public ListNode reverseKGroup(ListNode head, int k) { if(k == 0 || k == 1) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode tail = dummy, temp1 = head, temp2 = head, temp3 = head; while(temp1 != null) { int cnt = k; while(cnt > 1 && temp2.next != null) { // null should not be considered temp2 = temp2.next; cnt--; } if(cnt != 1) break; temp3 = temp2.next; temp2.next = null; // safe, break point for regular termination tail.next = null; temp2 = temp1.next; // safe, after revers the end would still be null while(temp1 != null) { temp2 = temp1.next; temp1.next = tail.next; tail.next = temp1; temp1 = temp2; } while(tail.next != null) { tail = tail.next; } tail.next = temp3; temp1 = temp3; temp2 = temp3; } return dummy.next; }
没有评论:
发表评论