题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
JZ24 反转链表
使用栈来对链表进行反转。注意考虑链表为空的情况,并且要记得最后的节点的next要设为null,否则会构成环
import java.util.*; /* 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; Stack<ListNode> stack = new Stack<>(); ListNode temp = head; while(temp != null) { stack.push(temp); temp = temp.next; } ListNode reverseHead = stack.pop(); ListNode p = reverseHead; while(!stack.isEmpty()) { p.next = stack.pop(); p = p.next; } p.next = null; return reverseHead; } }