206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
1. 栈
将原链表入栈,再初始化一个新链表,使栈中节点出栈,添加到新链表中,这样就完成了反转。
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
ListNode node = head;ListNode node2 = head;ListNode res = node2;
Stack<Integer> stack = new Stack<>();
while(node != null){
stack.push(node.val);
node = node.next;
}
while(!stack.isEmpty()){
node2.val = stack.pop();
node2 = node2.next;
}
return res;
}
2. 迭代
1 ——> 2 ——> 3——>null
null<——1 <——2 <——3
从头结点开始,将每一个节点的指向反转。
public ListNode reverseList(ListNode head) {
//迭代
ListNode prev = null;
ListNode curr = head;
while(curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
3. 递归
咱就是说,先全递归入栈了,假装后面已经排好序了,
1——> 2 <—— 3
改变 1和2 的指向就可以了,当前节点是1,2和3的顺序排好了,1.next.next = 1;
最后1.next = null;
public ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
//先全递归了,再依次回溯,执行下面的反转。
ListNode p = reverseList(head.next);
//当前节点是head,先出栈的是后面的部分,已经被反转,再反转前面部分就行了。当前节点的下一个的下一个指向当前节点。
head.next.next = head;
//头节点n1的下一个必须指向null
head.next = null;
return p;
}