题解 | #反转链表#
反转链表
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) { ListNode pre = null; ListNode next = null; while(head!=null){ //使用next节点保存head.next next = head.next; //反转:建立head到pre的指向 head.next = pre; //pre前移一位 pre = head; //head前移一位 head = next; } return pre; } }
- 不要把next节点和.next属性搞混淆
- 两个节点直接建立新的连接使用 .next 属性