Print Two Linked List One By One

题目地址:
https://instant.1point3acres.com/thread/199216

题目:

list, 交叉打印。


解题思路:
双指针来做。如果有多个list,可以用一个queue来做。

代码:



public class PrintTwoLinkedListOneByOne {

    public ListNode getElementOneByOne(ListNode head1, ListNode head2){
        List<Integer> rst = new ArrayList<>();
        int count = 0;
        ListNode l1 = head1;
        ListNode l2 = head2;
        ListNode dummy = new ListNode(-1);
        ListNode curr = dummy;
        while(l1 != null && l2 != null){
            if(count % 2 == 0){
                curr.next = new ListNode(l1.val);
                l1 = l1.next;
            }
            else{
                curr.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            count++;
            curr = curr.next;
        }
        if(l1 != null){
            curr.next = l1;
        }
        if(l2 != null){
            curr.next = l2;
        }
        return dummy.next;
    }

    public static void main(String[] args){
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        ListNode l2 = new ListNode(3);

        PrintTwoLinkedListOneByOne printTwoLinkedListOneByOne = new PrintTwoLinkedListOneByOne();
        ListNode rst = printTwoLinkedListOneByOne.getElementOneByOne(l1, l2);
        print(rst);
    }

    private static void print(ListNode rst) {
        while(rst != null){
            System.out.println(rst.val);
            rst = rst.next;
        }
    }

}


Comments

Popular Posts