具体看注解。有缘点个赞,一起加油! 对了,有一个用例运行超时。
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; class Node{ int address; int data; int next; public Node(int address, int data, int next) { this.address = address; this.data = data; this.next = next; } public Node() { } } public class Main{ public static void main(String[] args) throws IOException{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String [] s = r.readLine().trim().split("\\s+"); int start = Integer.parseInt(s[0]); int n = Integer.parseInt(s[1]); int k = Integer.parseInt(s[2]); Node arrin[] = new Node[100005]; // 进来的数据用数组装 while(n--!=0){//等价for循环 String [] arr_ = r.readLine().trim().split("\\s+"); int address = Integer.parseInt(arr_[0]); int data = Integer.parseInt(arr_[1]); int next = Integer.parseInt(arr_[2]); arrin[address] = new Node(); arrin[address].address =address; arrin[address].data =data; arrin[address].next =next; } // 定义头结点 Node temp = new Node();//搬运工 temp.address = start; temp.data = arrin[start].data; temp.next = arrin[start].next; // 将未首尾相接的链表数组通过集合组织起来 ArrayList<Node> list = new ArrayList<Node>(); while(temp.next!=-1) { list.add(new Node(temp.address,temp.data,temp.next)); temp.address = arrin[temp.next].address; temp.data = arrin[temp.next].data; temp.next = arrin[temp.next].next; } list.add(new Node(temp.address,temp.data,temp.next));//尾节点 reverse(list,k); for (int i = 0; i < list.size() - 1; i++) { System.out.printf("%05d %d %05d\n", list.get(i).address,list.get(i).data, list.get(i + 1).address); } int end = list.size() - 1; System.out.printf("%05d %d -1", list.get(end).address,list.get(end).data); } // reverse单纯交换Node,输出时实现next的转变 public static void reverse(ArrayList<Node> list, int k) { for (int i = 0; i + k <= list.size(); i += k) { for (int m = i + k - 1, n = i; m >= n; m--, n++) { Node temp = list.get(n); list.set(n, list.get(m)); list.set(m, temp); } } } }