【d45】【Java】【力扣】206.反转链表
思路
解法1:适用于数字不多的
1.把节点的数,都放进一个arraylist中
2.调用Collections.reverse(list)方法,将list转置
3.再遍历list,逐个放入数字
代码
解法1
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
static class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ArrayList<Integer> list = new ArrayList<>();
while (cur != null) {
list.add(cur.val);
cur=cur.next;
}
Collections.reverse(list);
cur=head;
for (int i = 0; i <= list.size() - 1; i++) {
cur.val=list.get(i);
cur=cur.next;
}
return head;
}
}
记录
总结
原文地址:https://blog.csdn.net/m0_74814985/article/details/142386436
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!