LeetCode-25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
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
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
public ListNode reverseKGroup(ListNode head, int k) {//链表 my ListNode nhead = new ListNode(0); nhead.next=head; ListNode nodek = nhead; while(null!=nodek&&null!=nodek.next){ ListNode nextnodek=nodek.next;//这k个结点的原始第一点,也是转换后的最后一个点 ListNode cur=nodek.next; ListNode pre =null; ListNode beh=cur; int num =0;
//判断是否还有k个点 while(null!=beh&&num<k){ beh=beh.next; num++; } if(num<k){ break; } num=0;
//移动后面的k个点 while(null!=cur&&num<k){ beh=cur.next; cur.next= pre; pre= cur; cur = beh; num++; } nodek.next=pre; nodek=nextnodek; nodek.next=cur; } return nhead.next; }
可读性更高一点的写法
public ListNode reverseKGroup(ListNode head, int k) {//mytip ListNode nhead = new ListNode(0); nhead.next=head; ListNode nodek = nhead; ListNode cur = head; int num =0; while(null!=cur){ num++; cur=cur.next; } cur=head; while(num>=k){ ListNode nextnodek=nodek.next; ListNode pre =null; for (int i = 0; i < k; i++) { head=head.next; cur.next=pre; pre =cur; cur=head; } nodek.next=pre; nodek=nextnodek; nodek.next=cur; num-=k; } return nhead.next; }
相关题
链表反转 LeetCode206 https://www.cnblogs.com/zhacai/p/10429295.html
两两交换链表中的节点LeetCode24 https://www.cnblogs.com/zhacai/p/10559271.html