题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here //首先处理特殊情况 if (head == null) { return head; } //rare保存每次反转的尾部,prehead保存上次反转前的头,这个头要接到下一次 ListNode rare = head; ListNode rslt = head; ListNode prehead = null; int counter = k; int epoch = 0; while (rare != null) { counter--; rare = rare.next; if (counter == 0) { epoch++; ListNode pre = rare; ListNode cur = head; while (cur != rare) { ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } if(prehead != null){ prehead.next = pre; System.out.println("prehead1"); } prehead = head; if (epoch == 1) { rslt = pre; } counter = k; head = rare; } } return rslt; } }
还是举一反三了反转链表的思路,但是多了两个任务
1.设置rare哨兵,监控每次反转的尾部。
2.设置prehead,将上一次反转后的尾部连接到下一次反转后的头部。
自认为写的没什么亮点,中规中矩的做题版代码