首页 > 试题广场 >

k个一组翻转链表

[编程题]k个一组翻转链表
  • 热度指数:658 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给你一个链表,每 k 个节点一组进行翻转,请返回翻转后的链表。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5


输入描述:
第一行:依次输入链表中的各个元素,以"#"结束

第二行:每组数量k


输出描述:
处理后的链表中的各个元素,以"->"连接
示例1

输入

1 2 3 4 5 #
2

输出

2->1->4->3->5
示例2

输入

1 2 3 4 5 #
3

输出

3->2->1->4->5
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
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);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String arrayStr = in.nextLine();
            int k = in.nextInt();
            ListNode head = new ListNode(0);
            ListNode p = head;
            String[] array =  arrayStr.split(" ");
            for (int i = 0; i < array.length - 1; i++) {
                p.next = new ListNode(Integer.parseInt(array[i]));
                p = p.next;
            }

            // 反转链表
            head = reverseK(head.next, k);
            printList(head);
        }
    }

    private static ListNode reverseK(ListNode head, int k) {
        // 如果反向反转  此处需要将整个链表反转

        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode pre = dummy;
        ListNode end = dummy;
        // 循环操作
        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++) {
                end  = end.next;
            }
            if (end == null) {
                break;
            }
            // 开始切断连线

            ListNode start = pre.next;
            ListNode nextStart = end.next;
            end.next = null;


            pre.next = reverseKGroup(start);
            start.next = nextStart;
            pre =  start;
            end = pre;

        }
        return dummy.next;

    }
    // 反转链表  改变指针方向
    private static ListNode reverseKGroup(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next ;
            curr.next = pre;
            pre = curr;
            curr = next;

        }
        return pre;
    }
    /**
     * 2->1->4->3->5
     */
    private static void printList(ListNode head) {
        StringBuilder sd = new StringBuilder();

        while (head != null) {
            sd.append(head.val);
            head = head.next;
            if (head != null ) {
                sd.append("->");
            }
        }
        System.out.println(sd.toString());

    }
}

编辑于 2024-01-23 10:41:08 回复(0)

热门推荐

通过挑战的用户

k个一组翻转链表