单链表反转
1、递归反转
递归反转法在反转当前节点之前先反转后续节点。这样从头结点开始,层层深入直到尾结点才开始反转指针域的指向。简单的说就是从尾结点开始,
public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node pre = reverse(head.next);
head.next.next = head;
head.next = null;
return pre;
}
2、遍历反转
递归反转法是从后往前逆序反转指针域的指向,而遍历反转法是从前往后反转各个结点的指针域的指向。
基本思路是:将当前节点cur的下一个节点 cur.getNext()缓存到temp后,然后更改当前节点指针指向上一结点pre。也就是说在反转当前结点指针指向前,先把当前结点的指针域用tmp临时保存,以便下一次使用.
public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}