题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ import java.util.*; public class Solution { public ListNode ReverseList(ListNode head) { if (head == null || head.next ==null){ return head; } Stack<ListNode> stack = new Stack<ListNode>(); ListNode cur = head; while(cur!=null){ stack.push(cur); System.out.println(cur.val); cur = cur.next; } head = stack.pop(); cur = head; // System.out.println(head.val); while(!stack.isEmpty()){ head.next = stack.pop(); // System.out.println(head.next.val); head = head.next; } // 最后的节点指向一定要为空,否则形成环 head.next = null; return cur; } }#练习题目,谁还有更好的解法#