链表反转
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class SingleLinkedList {
@Data
@AllArgsConstructor
@NoArgsConstructor
static class Node {
private Object value;
private Node next;
}
public static Node initList() {
Node head = null;
Node temp = null;
for (int i = 0; i < 5; i++) {
Node node = new Node(i, null);
if (i == 0) {
head = node;
} else {
temp.setNext(node);
}
temp = node;
}
return head;
}
public static void main(String[] args) {
Node node = SingleLinkedList.initList();
output(node);
Node reverseNode = reverseList(node);
output(
reverseNode
);
}
private static void output(Node node) {
while (null != node) {
System.out.println(node.getValue());
node = node.getNext();
}
}
public static Node reverseList(Node list) {
Node f = null;
if (null == list || null == list.getNext()) {
return list;
}
Node c = list;
Node next = null;
while (null != c) {
next = c.getNext();
c.next = f;
f = c;
c = next;
}
return f;
}
}