题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { private ListNode dummyNode; //基本思路:创建一个亚节点dummyNode,遍历head的时候,将遍历到的每个节点按照头插法插入dummyNode的 // 前面 public ListNode ReverseList(ListNode head) { if (head == null) return null; ListNode cur = head; while (cur != null) { //System.out.println("cur:"+cur.val); //对dummyNode进行头插法:需要操作节点的时候,单独创建一个节点,而不是操作链表 ListNode temp = new ListNode(cur.val); temp.next=dummyNode; dummyNode = temp; //System.out.println("dummyNode:"+dummyNode.val); cur = cur.next; } return dummyNode; } // 基本思路:获取链表的每个节点,然后按照从尾部遍历,依次修改链表的值 // public ListNode ReverseList(ListNode head) { // if(head == null) return null; // ListNode cur = head; // ListNode newHead = head; // ArrayList<Integer> list = new ArrayList<>(); // //找出head每个节点值 // while (cur != null) { // list.add(cur.val); // cur = cur.next; // } // int n = list.size(); // //修改head的节点值 // for (int i = n - 1; i >= 0; i--) { // //System.out.println(list.get(i)); // newHead.val = list.get(i); // newHead = newHead.next; // } // return head; // } }