LeetCode --- ListNode 工具加强

增加两个链表的方法,一个可以根据数组构造对象,一个可以比较两个链表。

public class ListNode {

    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }

    ListNode(int[] nums) {
        ListNode target = new ListNode(nums[0]);
        ListNode head = target;
        for (int i = 1; i < nums.length; i++) {
            target.next = new ListNode(nums[i]);
            target = target.next;
        }
        this.val = head.val;
        this.next = head.next;
    }

    public static boolean compareTwoListNode(ListNode node1, ListNode node2) {
        while (node1 != null) {
            if (node2 == null) {
                return false;
            }
            if (node1.val != node2.val) {
                return false;
            }
            node1 = node1.next;
            node2 = node2.next;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/ydonghao2/article/details/80411951
今日推荐