【算法】链表翻转的两种写法
2024-04-01 本文已影响0人
王月亮17
初始化
ListNode listNode5 = new ListNode(5, null);
ListNode listNode4 = new ListNode(4, listNode5);
ListNode listNode3 = new ListNode(3, listNode4);
ListNode listNode2 = new ListNode(2, listNode3);
ListNode listNode1 = new ListNode(1, listNode2);
doReverse(listNode1);
遍历
private static ListNode doReverse(ListNode head) {
ListNode prev = null, next;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
递归
private static ListNode doReverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = doReverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}