1.题目描述
输入一个链表,反转链表后,输出新链表的表头。
2.解题思路
-
用一个栈stack依次存储ListNode里面的值,因为stack的特点是先进后出,故依次弹出即为反转链表
-
用一个链表temp依次存储弹出的值,依次next存入下一个链表值,链表res指向这个temp的头节点
-
反转链表的结果为res.next,因为我们之前设temp的头节点为-1(自己设的)。
3.代码
/* public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
Stack<Integer> stack = new Stack<>();
while (head!=null){
stack.push(head.val);
head = head.next;
}
ListNode temp = new ListNode(-1);
ListNode res = temp;
while(stack.size()!=0){
temp.next = new ListNode(stack.pop());
temp = temp.next;
}
return res.next;
}
}