首页 > 代码库 > reverse-nodes-in-k-group
reverse-nodes-in-k-group
https://leetcode.com/problems/reverse-nodes-in-k-group/
https://leetcode.com/mockinterview/session/result/xjlzcwc/
链表分批倒置,还是有点绕的。用了三个临时变量来处理。需要细心,也需要掌握类似经验。
package com.company; import java.util.*; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (k <= 1) { return head; } ListNode ret = new ListNode(0); ret.next = head; ListNode cur = ret; ListNode next = head; ListNode first = null; ListNode second = null; ListNode third = null; while (true) { int i=0; for (; i<k; i++) { if (next == null) { break; } next = next.next; } if (i < k) { break; } first = cur.next; second = first.next; for (i=0; i<k-1; i++) { third = second.next; second.next = first; first = second; second = third; } cur.next.next = next; third = cur.next; cur.next = first; cur = third; } return ret.next; } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: ListNode ln1 = new ListNode(1); ListNode ln2 = new ListNode(2); ListNode ln3 = new ListNode(3); ListNode ln4 = new ListNode(4); ListNode ln5 = new ListNode(5); ln1.next = ln2; ln2.next = ln3; ln3.next = ln4; ln4.next = ln5; ListNode ret = solution.reverseKGroup(ln1, 3); for (int i=0; i<5; i++) { System.out.printf("ret:%d\n", ret.val); ret = ret.next; } System.out.println(); } }
reverse-nodes-in-k-group
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。