反转链表

反转链表

http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

栈的解法:先进后出

import java.util.*;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        // 生成新的反转链表
        ListNode resultNode = stack.pop();
        ListNode tempNode = resultNode;
        while (!stack.isEmpty()) {
            tempNode.next = stack.pop();
            tempNode = tempNode.next;
        }
        // 将反转链表的最后置为null
        tempNode.next = null;
        return resultNode;
    }
}
全部评论

相关推荐

就是大飞舞:不能发,我暑假找实习的时候就被坑过,把你简历锁了,然后不给你推进度,你还投不了别的部门
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务