206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。https://leetcode.cn/problems/reverse-linked-list/
示例 :
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
方法一:双指针迭代
代码示例:
/**
* 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) {
ListNode pre =null;
ListNode cur =head;
while(cur != null){
ListNode temp =cur.next;
cur.next =pre;
pre=cur;
cur =temp;
}
return pre;
}
}
思路分析:
方法二:用栈实现
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack =new Stack<>();
ListNode start =new ListNode(0,new ListNode(0));
ListNode temp =start;
while(head !=null){
stack.push(head);
head = head.next;
}
while(!stack.isEmpty()){
temp.next =stack.pop();
temp =temp.next;
}
temp.next =null;
return start.next;
}
思路分析:
方法三:头插法
public ListNode reverseList(ListNode head) {
ListNode node =null;
for(ListNode x=head;x !=null;x=x.next){
node =new ListNode(x.val,node);
} return node;
}
思路分析:
附:
-
方法二建议使用Deque代替stack(官方推荐Dequehttps://blog.csdn.net/Tommy_____/article/details/106445631)
-
Deque
允许两头都进,两头都出,这种队列叫双端队列(Double Ended Queue),简称Deque。
Java集合提供了接口Deque来实现一个双端队列,它的功能:
①既可以添加到队尾,也可以添加到队首;
②既可以从队首获取,又可以从队尾获取。
-
Stack的入栈和出栈的操作:
①把元素压栈:push(E);
②把栈顶的元素“弹出”:pop(E);
③取栈顶元素但不弹出:peek(E)。 -
在Java中,我们用Deque可以实现Stack的功能:
①把元素压栈:push(E)/addFirst(E);
②把栈顶的元素“弹出”:pop(E)/removeFirst();
③取栈顶元素但不弹出:peek(E)/peekFirst()。