举例1:
输入: [1,2,3,4,5],
输出: [5,4,3,2,1].
举例2:
输入: []
输出:[]
思路:方法有三种,分别是递归,栈,双指针,本篇使用栈,原理为利用栈的后进先出特性,将链表节点依次压入栈中,紧接着将其依次弹出栈,以用来构建新的反转链表
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if (head == null) { return null; } //将链表节点依次压入栈中 Stack<ListNode> nodeStack = new Stack<>(); while (head != null) { nodeStack.push(head); head = head.next; } //依次弹出栈,构建新的反转链表 ListNode reverseList = nodeStack.pop(); ListNode currect = reverseList; while (!nodeStack.isEmpty()) { currect.next = nodeStack.pop(); currect = currect.next; } currect.next = null; return reverseList; } }