每k个结点一组翻转链表
题目描述
给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
说明:
- 你需要自行定义链表结构,将输入的数据保存到你的链表中;
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换;
- 你的算法只能使用常数的额外空间。
输入描述:
第一行输入是链表的值
第二行输入是K的值,K是大于或等于1的整数
输入形式为:
1 2 3 4 5
2
输出描述:
当 k = 2 时,应当输出:
2 1 4 3 5
当 k = 3 时,应当输出:
3 2 1 4 5
当k=6时,应当输出:
1 2 3 4 5
示例1
输入
1 2 3 4 5
2
输出
2 1 4 3 5
import java.util.Scanner;
public class Main {
static class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int k = scanner.nextInt();
String[] strings = s.split(" ");
ListNode head = new ListNode(-1);
ListNode t = head;
for (int i = 0; i < strings.length; i++) {
ListNode p = new ListNode(Integer.parseInt(strings[i]));
t.next = p;
t = t.next;
}
head = head.next;
ListNode q = reverseKGroup(head, k);
while (q != null) {
System.out.print(q.val + " ");
q = q.next;
}
}
//实现从头结点到尾结点的翻转
public static ListNode reverse(ListNode head,ListNode tail) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode next = null;
while (pre != tail) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
//遍历链表,寻找k个位一组的子链表
public static ListNode reverseKGroup(ListNode head,int k) {
if (head == null || head.next == null || k <= 1) {
return head;
}
//从当前链表头结点开始遍历,找到k个待翻转节点的尾结点currentTail
ListNode currentTail = head;
for (int i = 1; i < k; i++) {
currentTail = currentTail.next;
//链表节点不足k个,不用翻转链表
if (currentTail == null) {
return head;
}
}
//保存下一组k个待翻转链表的头结点
ListNode nextHead = currentTail.next;
//翻转k个结点组成的链表
reverse(head,currentTail);
//防止断链
head.next = reverseKGroup(nextHead,k);
return currentTail;
}
}
网友其他解答:
import java.util.*;
class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()){
String[] str = sc.nextLine().split(" ");
int k = Integer.valueOf(sc.nextLine());
ListNode pre = new ListNode(Integer.valueOf(str[0]));
ListNode head = pre;
for (int i=1;i<str.length;i++){
ListNode node = new ListNode(Integer.valueOf(str[i]));
pre.next = node;
pre = node;
}
pre.next = null;
head = reverse(head, k);
while (head != null){
System.out.print(head.val+" ");
head = head.next;
}
}
}
public static ListNode reverse(ListNode head, int k){
ListNode tmp = head;
for (int i=1;i<k&&tmp!=null;i++)
tmp = tmp.next;
if (tmp == null) return head;
ListNode Lhead = tmp.next;
tmp.next = null;
ListNode newHead = revK(head);
ListNode newLHead = reverse(Lhead, k);
head.next = newLHead;
return newHead;
}
public static ListNode revK(ListNode head){
ListNode tmp = null, pre = null;
while (head != null){
tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
}
return pre;
}
}