思路
这种反转链表首先会想到借助栈来实现。按照从头到尾的顺序压栈,然后弹栈,结果就是一个反转链表。
这里我写了两个方法,异曲同工。
代码实现
import java.sql.Statement;
import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        if (stack.isEmpty()) {
            return null;
        }
        ListNode node = stack.pop();
        ListNode dummy = node;
        while (!stack.isEmpty()) {
            node.next = stack.pop();
            node = node.next;
        }
        node.next = null;
        return dummy;
    }
    public ListNode ReverseList2(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        if (head == null) {
            return null;
        }
        while (true) {
            if (head.next == null) {
                stack.push(head.val);
                break;
            }
            stack.push(head.val);
            head = head.next;
        }
        if (stack.isEmpty()) {
            return null;
        }
        ListNode node = new ListNode(stack.pop());
        ListNode dummmy = node;
        while (!stack.isEmpty()) {
            node.next = new ListNode(stack.pop());
            node = node.next;
        }
        return dummmy;
    }
    public static void main(String[] args) {
        ListNode node = null;
        Solution solution = new Solution();
        solution.ReverseList2(node);
    }
}
class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
} 
京公网安备 11010502036488号