剑指offer_【15】反转链表

1.题目描述

输入一个链表,反转链表后,输出新链表的表头。

2.解题思路

  1. 用一个栈stack依次存储ListNode里面的值,因为stack的特点是先进后出,故依次弹出即为反转链表

  2. 用一个链表temp依次存储弹出的值,依次next存入下一个链表值,链表res指向这个temp的头节点

  3. 反转链表的结果为res.next,因为我们之前设temp的头节点为-1(自己设的)。

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 /* 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;
}
}
文章目录
  1. 1. 1.题目描述
  2. 2. 2.解题思路
  3. 3. 3.代码
| 139.6k