1.建立虚拟头节点辅助反转
public static ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = next;
}
return dummy.next;
}
2.直接操作链表实现反转
public 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 cur;
}