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: 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 ,逆这部分链表一次。
1 一开始没理解题目意思,以为是只有把前半部分k给逆转就行了。结果wrong了,不过好在,前面的转换思路对我后面解题也是有帮助的。
2 关键点有两个:
a 什么时候逆转?
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(k<=1||head==null){ return head; } ListNode dummy = new ListNode(Integer.MIN_VALUE); dummy.next=head; ListNode pre = dummy; ListNode cur = head; for(int i=1;cur!=null;i++){ if(i%k==0){ pre = reverse(pre,cur); cur = pre.next; } else{ cur=cur.next; } } return dummy.next; }
// outpre inpre inend outbound 分别代表4个关键点 public ListNode reverse(ListNode outpre ,ListNode inend){ ListNode inpre = outpre.next; ListNode cur = inpre.next; ListNode outbound = inend.next; ListNode repre = inpre; outpre.next=inend; while(cur!=outbound){ ListNode temp = cur.next; cur.next=inpre; inpre=cur; cur= temp ; } repre.next=outbound; return repre; } }