题目
输入一个链表并反转
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
以下两种解法,都很重要。理解并背下来
建立虚拟节点辅助反转
public static ListNode reverseList(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 ListNode reverseList(ListNode head ) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}