基础知识 + 基本操作(青铜挑战)
-
什么是链表反转呢?如图所示:
-
常见的链表反转的方法:虚拟头节点、直接反转、递归
-
虚拟头节点,具体代码如下:
/**
* 方法1:虚拟头结点
*
* @param head
* @return
*/
public static ListNode reverseListByDummyNotCreate(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
-
如图所示:
-
直接反转,具体代码如下:
/**
* 方法2:直接反转
*
* @param head
* @return
*/
public static ListNode reverseListSimple(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
-
如图所示:(2023/07/28午)