【hot100-java】K 个一组翻转链表
链表篇
参考题解
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseKGroup(ListNode head, int k) {//哨兵节点ListNode dummy=new ListNode(0);dummy.next=head;//两个节点同位置一起从哨兵位置出发ListNode pre=dummy;ListNode end=dummy;while(end.next!=null){for(int i=0;i<k&&end!=null;i++) end=end.next;if(end==null) break;ListNode start=pre.next;ListNode next=end.next;end.next=null;pre.next=reverse(start);start.next=next;pre=start;end=pre;}return dummy.next;}//翻转链表private ListNode reverse(ListNode head){//前后节点ListNode pre =null;ListNode curr=head;//翻转相邻节点--》翻转链表while(curr!=null){ListNode next=curr.next;curr.next=pre;pre=curr;curr=next;}//pre代表最后一个节点return pre;}
}