题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
题目如下:
/** * 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) { HashMap<Integer,ListNode> hash=new HashMap<Integer,ListNode>(); int count=0; //将每个节点放入hashmap中,用count计数 while(head!=null){ hash.put(count++,head); head=head.next; } //倒序放入新的链表中,空指针中依次放入节点 ListNode list=new ListNode(0); ListNode pre=list; while(--count>=0){ pre.next=hash.get(count); pre=pre.next; } pre.next=null; return list.next; } }