题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null || head.next == null) { return head; } ListNode result = head; ListNode tempHead = head.next; result.next = null; while(tempHead != null) { ListNode tempNext = tempHead.next; tempHead.next = result; result = tempHead; tempHead = tempNext; } return result; } }
对于java的链表而言,在将head赋值给result之后,不能直接进行result.next=null,这样会导致head的后续值全丢失,这是因为java的赋值是进行引用赋值,操作的还是同一个地址保存的数值,所以在进行result.next=null之前需要将head.next的值进行保存
#悬赏#