题解 | #反转链表#
反转链表
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; ListNode pre=null; ListNode next=null; while(head!=null){ next=head.next;//先保存head下一个节点信息,保证下一个节点不会因为失去head 导致链表断裂 head.next= pre;//链表指向方向变化 pre=head;//遍历节点 head=next; } return pre; } }