Reverse Linked List
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummyNode = new ListNode(-1);
while (head != null) {
//copy head.val / head.next to temp(保存head 的值 → temp为oldHead)
ListNode temp = head;
//copy head.next.val and head.next.next to head (head 移动)
head = head.next;
//将temp指向dummyNode指向的位置,也就是null (oldHead 指向 null)
temp.next = dummyNode.next;
//将 dummyNode 指向 temp;
dummyNode.next = temp;
}
return dummyNode.next;
}
}
最后更新于
这有帮助吗?