题解 | 链表中的节点每k个一组翻转
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; public class Main { static class ListNode{ int val; ListNode next; ListNode(int val){ this.val = val; } } // 这里全是输入处理 public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ String str = in.nextLine(); int k = in.nextInt(); ListNode head = new ListNode(-1); ListNode p = head; String[] strArray = str.split(" "); for(int i = 0; i < strArray.length - 1; i++){ p.next = new ListNode(Integer.parseInt(strArray[i])); p = p.next; } head = reverseK(head.next, k); printList(head); } } // 输出处理 private static void printList(ListNode head) { while(head != null){ System.out.print(head.val); if(head.next != null){ System.out.print("->"); } head = head.next; } } // 核心程序 private static ListNode reverseK(ListNode head, int k) { if(k == 1 || head == null || head.next == null){ return head; } ListNode a = head, b = head; for(int i = 0; i < k; i++){ if(b == null){ return head; } b = b.next; } ListNode newHead = reverse(a, b); head.next = reverseK(b, k); return newHead; } private static ListNode reverse(ListNode a, ListNode b) { ListNode pre = null, cur = a; while(cur != b){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }