题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
本题考查的是对链表的结构的掌握
对于每一个节点,需要保存其下一节点,然后将其下一节点指向上一个节点。依次遍历所有节点即可。
需要注意的点在于第一个节点要指向null,还需要注意遍历的终止条件。
Java题解如下:
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode ReverseList (ListNode head) { // write code here ListNode pre = null; while(head != null) { ListNode next = head.next; head.next = pre; pre = head; head = next; } return pre; } }