题解 | #反转单向链表#(三指针法)
反转单向链表
https://www.nowcoder.com/practice/b66a251dec8847f386bbe6cd96b7e9c8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.List; class Node { private Node next; private int value; public Node(int value) { this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public static Node createNodeList(Integer[] values) { Node head = new Node((values[0])); Node node = head; for (int i = 1; i < values.length; i++) { Node newNode = new Node(values[i]); node.next = newNode; node = newNode; } return head; } public static Node createNodeList(String[] values) { Node head = new Node(Integer.parseInt(values[0])); Node node = head; for (int i = 1; i < values.length; i++) { Node newNode = new Node(Integer.parseInt(values[i])); node.next = newNode; node = newNode; } return head; } } class LinkReverse { public static StringBuilder linkReverse(Node head, int len) { StringBuilder sb = new StringBuilder(); if (len >= 2) { Node n1=head; Node n2=n1.getNext(); Node n3=n2.getNext(); n1.setNext(null); while(n2!=null){ n2.setNext(n1); n1=n2; n2=n3; if(n3!=null)n3=n3.getNext(); } head=n1; } Node n=head; while(n!=null){ sb.append(n.getValue()).append(" "); n=n.getNext(); } return sb; } } public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); String[] strings1 = input.readLine().split(" "); Node head1 = Node.createNodeList(strings1); int m = Integer.parseInt(input.readLine()); String[] strings2 = input.readLine().split(" "); Node head2 = Node.createNodeList(strings2); System.out.println(LinkReverse.linkReverse(head1, n).toString()); System.out.print(LinkReverse.linkReverse(head2, m).toString()); } }
#22届毕业生你还好吗##字节跳动收购沐瞳科技##黄峥辞任拼多多董事长#