题解 | #反转链表#
反转链表
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) return null; /* 需要的辅助变量:cur,next cur指向即将被倒叙插入的数据元素,next为了临时保存原链表下一个元素的地址, 为了能找到下一个元素,不然直接更改cur.next可能会丢失后边的元素 另外,由于第一个节点就存放数据,因此需要对第一个节点进行特殊处理, 不要把特殊情况放到循环中,否则会让程序难以理解 对第一个节点的处理,注意要将next赋值为null */ ListNode list = null; ListNode cur = null; ListNode next = null; cur = head.next; list = head; list.next = null; while (cur != null) { next = cur.next; cur.next = list; list = cur; cur = next; } return list; } }