手写链表反转(入门)
链表反转在算法题中出现的频率特别高,是链表最重要的问题。
示例:
输入:head = 1->2->3->4->5
输出:5->4->3->2->1
方法一:建立虚拟头结点辅助反转
先建立一个虚拟的结点ans,并且令ans.next = head,这样就会方便很多。
每次从旧的链表拆下,链接到ans后面即可完成反转,代码如下:
/**
* 方法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;
}
方法二:直接操作链表实现反转
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;
}