// 链表反转的思路:依次将head后面的节点插入到last后面去即可
// 节点的删除和插入
public static Node reverseLinkedList(Node head) {
if (head != null) {
Node last = head;
while (last.next != null) {
last = last.next;
}
while (head.next != last) {
// 获取head后面的第一个节点
Node temp = head.next;
// 删除head后面的第一个节点
head.next = temp.next;
// 将删除的节点插入last节点后面
temp.next = last.next;
last.next = temp;
}
return head;
} else {
throw new IllegalArgumentException("head must be not null!");
}
}
// 节点的删除和插入
public static Node reverseLinkedList(Node head) {
if (head != null) {
Node last = head;
while (last.next != null) {
last = last.next;
}
while (head.next != last) {
// 获取head后面的第一个节点
Node temp = head.next;
// 删除head后面的第一个节点
head.next = temp.next;
// 将删除的节点插入last节点后面
temp.next = last.next;
last.next = temp;
}
return head;
} else {
throw new IllegalArgumentException("head must be not null!");
}
}