25. K 个一组翻转链表
目录
题目链接
题目
解题思路
代码
题目链接
25. K 个一组翻转链表 - 力扣(LeetCode)
题目
解题思路
设置一个尾指针,如果尾指针在遍历时就是null,那就直接返回,否则,就翻转当前的区域指针,知道一个pre,和下一个区域的头指针next,这样翻转后可以拼接起来
代码
/*** 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) {if(head==null) return null;ListNode dunmyNode=new ListNode(-1);dunmyNode.next=head;ListNode end=dunmyNode;ListNode pre=dunmyNode;while(end!= null){for(int i=0;i<k;i++){end=end.next;if(end==null){return dunmyNode.next;}} ListNode start,next;start=pre.next;next=end.next;end.next=null;pre.next=reverse(start);start.next=next;pre=start;end=pre;}return dunmyNode.next;}public ListNode reverse(ListNode head){ListNode pre,cur;pre=null;cur=head;while(cur!=null){ListNode next=cur.next;cur.next=pre;pre=cur;cur=next;}return pre;}
}