题解 | #每K个一组反转链表#

每K个一组反转链表

https://www.nowcoder.com/practice/a632ec91a4524773b8af8694a51109e7

import java.util.Scanner;

class MySeqList {
    class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public void SeqList_Push_Back(int val) {
        ListNode Node = new ListNode(val);
        if (head == null) {
            head = Node;
            return;
        }
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
        }
        tail.next = Node;
    }
    public ListNode resvertall(ListNode head){
      ListNode prev =null;
      ListNode cur = head;
      while(cur!=null){
          ListNode Next=cur.next;
          cur.next=prev;
          prev=cur;
          cur=Next;
      }
      return prev;
    }
    public ListNode resver(ListNode head,int k) {
        ListNode Node = new ListNode(0);
        Node.next = head;
        ListNode prev = Node;
        ListNode end = Node;
        ListNode start = Node.next;
        while (end.next != null) {
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }
            if (end == null) {
                break;
            }
            ListNode Next = end.next;
            end.next = null;
            ListNode tmp = resvertall(start);
            prev.next=end;
            start.next = Next;
            prev = start;
            end = start;
            start = start.next;
        }
        return Node.next;
    }
    public void display(ListNode head) {

        if (head == null) {
            return;
        }
        ListNode tail = head;
        while (tail != null) {
            System.out.print(tail.val+" ");

            tail = tail.next;
        }
    }
}
public class Main {
    public static void creat(String s, MySeqList rea) {
        String[] str = s.split(" ");
        int a = 0;
        for (int i = 0; i < str.length; i++) {
            a = Integer.parseInt(str[i]);
            rea.SeqList_Push_Back(a);
        }
    }
    public static void main(String[] args) {
        MySeqList mySeqList = new MySeqList();
        MySeqList mySeqList1 = new MySeqList();
        MySeqList mySeqList2 = new MySeqList();
        Scanner scanner = new Scanner(System.in);
        String str =scanner.nextLine();
        int k = scanner.nextInt();
        creat(str,mySeqList);
      MySeqList.ListNode tmp= mySeqList1.resver(mySeqList.head,k);
       mySeqList2.display(tmp);
    }
}
全部评论

相关推荐

11-01 20:03
已编辑
门头沟学院 算法工程师
Amazarashi66:这种也是幸存者偏差了,拿不到这个价的才是大多数
点赞 评论 收藏
分享
10-06 12:46
门头沟学院 Java
跨考小白:定时任务启动
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-26 16:06
已编辑
快手电商 后端 23k-35k
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务