题目描述:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
代码实现:
/*** 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 dummyHead = new ListNode(0);dummyHead.next = head;ListNode pre = dummyHead;while(head != null) {ListNode tail = pre;int step = k;// k步一组while(step > 0) {step--;tail = tail.next;if (tail == null) { // 最后不足k的一组return dummyHead.next;}}// 记录下一个结点,防止断链ListNode next = tail.next;// 翻转reversePartOfListNode(head,tail);ListNode tempHead = tail;ListNode tempTail = head;// 重新接链pre.next = tempHead;tempTail.next = next;// 移动结点pre = tempTail;head = tempTail.next;}return dummyHead.next;}// 翻转部分链表public void reversePartOfListNode(ListNode head, ListNode tail) {ListNode pre = tail.next;ListNode cur = head;while(pre != tail) {ListNode next = cur.next;cur.next = pre;pre = cur;cur = next;}}}
