Leetcode-206 反转链表

作者: itbird01 | 来源:发表于2021-09-24 08:08 被阅读0次

206. 反转链表

解题思路

1.遍历转换为数组
2.数组反转,new ListNode

解题遇到的问题

1.头结点初始化和之后结点,变量赋值不同

后续需要总结学习的知识点

1.链表的遍历、插入、删除、添加,JDK源码阅读List的不同实现

##解法1
import java.util.ArrayList;
import java.util.List;

class Solution {
    public static void main(String[] args) {
        reverseList(new ListNode(1, new ListNode(2,
                new ListNode(3, new ListNode(4, new ListNode(5))))));
    }
    /**
     * 1.遍历转换为数组
     * 2.数组反转,new ListNode
     */
    public static ListNode reverseList(ListNode head) {
        List<Integer> list = new ArrayList<Integer>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }

        ListNode result = null;
        for (int i = list.size() - 1; i >= 0; i--) {
            if (i == list.size() - 1) {
                head = new ListNode(list.get(i));
                result = head;
            } else {
                ListNode temp = new ListNode(list.get(i));
                head.next = temp;
                head = head.next;
            }
        }
        return result;
    }

    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;
        }
    }
}

相关文章

网友评论

    本文标题:Leetcode-206 反转链表

    本文链接:https://www.haomeiwen.com/subject/wnhlgltx.html