标签:system ide vat head lis turn override ring rev
public class SinglyLinkedList<T> {
// 一个空的头节点
private final Node head = new Node(null);
private Node tail = head;
@SafeVarargs
public final void addAll(T... data) {
if (data == null) return;
for (T datum : data) {
tail.next = new Node(datum);
tail = tail.next;
}
}
public void reverse() {
Node index = head.next, pre = head;
if (index == null || index.next == null) return;
Node des = index.next, newTail = index;
do {
index.next = pre;
pre = index;
index = des;
if (index != null)
des = index.next;
} while (index != null);
tail = newTail;
tail.next = null;
head.next = pre;
}
@Override
public String toString() {
Node i = head.next;
StringBuilder buffer = new StringBuilder();
while (i != null) {
buffer.append(" ").append(i.data).append(" ");
i = i.next;
}
return buffer.toString();
}
@Data
@NoArgsConstructor
@AllArgsConstructor
private class Node {
private T data;
private Node next;
public Node(T data) {
this.data = data;
}
}
}
单元测试:
class SinglyLinkedListTest {
@Test
void reverse() {
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.addAll(5, 4, 3, 2, 1);
list.reverse();
System.out.println(list.toString());
}
}
输出:
1 2 3 4 5
标签:system ide vat head lis turn override ring rev
原文地址:https://www.cnblogs.com/xch-jiang/p/14386306.html