算法通关村第二关|终于学会链表反转了
先看题目Leetcode206 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
解法一:创建虚拟头结点辅助反转
如下图所示,先创建一个虚拟头结点ans,并令ans.next=ListNode(1),每次我们从旧的链表取出一个结点接到ans后面,最后返回ans.next就是反转后的链表
public ListNode reverseListByDummy(ListNode head) {
ListNode dummyHead = new ListNode(0);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = dummyHead.next;
dummyHead.next = cur;
cur = next;
}
return dummyHead.next;
}
解法二:直接操作链表
public ListNode reverseListBySimple(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}