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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Node firstNode = createNode(4); System.out.println("origin:" + firstNode); resortNode(firstNode); System.out.println("resorted:" + firstNode);
firstNode = createNode(5); System.out.println("origin:" + firstNode); resortNode(firstNode); System.out.println("resorted:" + firstNode); }
private static void resortNode(Node node) { List<Node> list = new ArrayList<>(); while (node != null) { list.add(node); node = node.next; }
for (int i = 0; i < list.size(); i++) { Node head = list.get(i); Node tail = list.get(list.size() - i - 1); if (head == tail) { head.next = null; break; } if (head.next == tail) { tail.next = null; break; } tail.next = head.next; head.next = tail; } }
private static Node createNode(int num) { Node tail = new Node(num, null); for (int i = num - 1; i > 0; i--) { tail = new Node(i, tail); } return tail; }
static class Node { public Node(int value, Node next) { this.value = value; this.next = next; }
int value; Node next;
@Override public String toString() { return value + (next == null ? "" : ("->" + next)); } } }
|