题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
题目如下:
解法一:hashmap
/**
* 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;
}
}
解法二:三指针法(pre,cur,next)
/**
* 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) {
//当前要处理的指针: cur;
//tip:链表最多用三个指针,pre,cur,next
ListNode pre=null;//预返回的链表
ListNode cur=head;//用于当前操作的指针
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}