反转链表

反转链表

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;
    }
}
全部评论

相关推荐

练习JAVA时长两年半:qps 30000
点赞 评论 收藏
分享
饼子吃到撑:当我看到外企的时候,我就知道这大概率可能是真的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务