手写链表反转
链接:206. 反转链表
1. 建立虚拟头节点辅助反转
这里其实相当于开辟了一条新的链表。将原来的链表进行从头遍历,再将遍历到的元素插入到新的链表中。最后只需要返回虚拟头节点的next即可。总体思路是比较的简单。
public static ListNode reverseList(ListNode head) {
ListNode dummyNode = new ListNode();
ListNode cur = head;
while(cur != null) {
// 保证始终插入在头部
ListNode next = dummyNode.next;
cur.next = dummyNode.next;
dummyNode.next = cur;
cur = next;
}
return dummyNode.next;
}
2. 直接操作链表反转
核心在于不断地调整两个节点的相互关系,实现指向关系的反转
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
3. 递归
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
无法理解,日后研究…