LeetCode25. Reverse Nodes in k-Group

题目:题目链接

题意:给出一个链表和一个整数k,要求链表每k个节点反转一次,如果最后剩余不足k个节点,则不反转。

思路:数据结构链表基础题,注意边界控制就好。

PS:最近一段时间应该都会用Java做题了,Java学的太烂了,这么一道题还要各种查Java基础知识。

ac代码:

 1 class Solution {
 2 
 3     public ListNode reverseKNode(ListNode l, ListNode r) {
 4 
 5         ListNode f = l.next;
 6         ListNode cur = f.next;
 7 
 8         while(cur != r) {
 9             f.next = cur.next;
10             cur.next = l.next;
11             l.next = cur;
12             cur = f.next;
13         }
14         return f;
15     }
16 
17     public ListNode reverseKGroup(ListNode head, int k) {
18 
19         if(head == null || k == 1) return head;
20 
21         ListNode ans = new ListNode(0);
22         ans.next = head;
23         ListNode l, r;
24         l = ans;
25         int count = 0;
26         while(head != null) {
27             count++;
28             r = head.next;
29             if(count % k == 0) {
30                 l = reverseKNode(l, r);
31             }
32             head = r;
33         }
34         return ans.next;
35     }
36 }
原文地址:https://www.cnblogs.com/fan-jiaming/p/11863617.html