程序员代码面试指南第二版 23.将单链表的每K个节点之间逆序
题目描述
给定一个单链表,实现一个调整单链表的函数,使得每 K 个节点之间的值逆序,如果最后不够 K 个节点一组,则不调整最后几个节点。
输入描述:
第一行一个整数 n,n 表示单链表的节点数量。
第二行 n 个整数 val 表示链表的各个节点的值。
第三行一个整数 K。
输出描述:
在给定的函数内返回链表的头指针。
示例1
输入
5
1 2 3 4 5
3
输出
3 2 1 4 5
第一次做; 核心:找好上一组的最后一个节点, 下一组的第一个节点, 当前组反转后的最后一个节点; 创建临时头结点
import java. util. Scanner;
public class Main {
public static void main ( String[ ] args) {
Scanner sc = new Scanner ( System. in) ;
int n = Integer. parseInt ( sc. nextLine ( ) ) ;
String[ ] str = sc. nextLine ( ) . split ( " " ) ;
int k = Integer. parseInt ( sc. nextLine ( ) ) ;
if ( n< 1 || k< 1 )
return ;
ListNode head = new ListNode ( Integer. parseInt ( str[ 0 ] ) ) ;
ListNode curr = head;
for ( int i= 1 ; i< n; i++ ) {
curr. next = new ListNode ( Integer. parseInt ( str[ i] ) ) ;
curr = curr. next;
}
ListNode temp = new ListNode ( 0 ) ;
temp. next = head;
ListNode pre = temp;
ListNode after = pre;
curr = head;
ListNode left = pre, right;
ListNode last;
int count = k;
while ( curr!= null) {
while ( count > 0 && after != null) {
after = after. next;
count-- ;
}
if ( after== null)
break ;
after = after. next;
count = k;
last = curr;
while ( curr!= after) {
right = curr. next;
curr. next = left;
left = curr;
curr = right;
}
pre. next = left;
last. next = after;
pre = last;
after = last;
}
curr = temp. next;
while ( curr!= null) {
System. out. print ( curr. val+ " " ) ;
curr = curr. next;
}
}
public static class ListNode {
int val;
ListNode next;
ListNode ( int val) {
this . val = val;
}
}
}