题解 | #每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); } }