1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.util.StringJoiner;
public class ReverseLinkedList { public static void main(String[] args) { Node node = prepareNodeList(); printNodeList(node); Node pre = null, t = node, next; while (t != null) { next = t.next; t.next = pre; pre = t; t = next; } printNodeList(pre); }
static Node prepareNodeList() { int[] arr = new int[]{2, 4, 5, 6, 7, 8, 9}; Node head = new Node(-1); Node t = head; for (int i : arr) { Node node = new Node(i); t.next = node; t = node; } return head.next; }
static void printNodeList(Node node) { StringJoiner sj = new StringJoiner("-->"); while (node != null) { sj.add(String.valueOf(node.x)); node = node.next; } System.out.println(sj); }
static class Node { int x; Node next;
Node(int x) { this.x = x; } } }
|