Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21. Merge Two Sorted Lists #20

Open
Luchanaaaaa opened this issue Mar 30, 2023 · 1 comment
Open

21. Merge Two Sorted Lists #20

Luchanaaaaa opened this issue Mar 30, 2023 · 1 comment

Comments

@Luchanaaaaa
Copy link
Owner

Luchanaaaaa commented Mar 30, 2023

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dammy = new ListNode(0);
        ListNode cur = dammy;
        while (list1!= null|| list2!=null){
            if(list1 == null){
                cur.next = list2;
                break;
            }else if(list2 == null){
                cur.next = list1;
                break;
            }
            if(list1.val <= list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        return dammy.next;

    }
}
@Luchanaaaaa
Copy link
Owner Author

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode pointer1 = list1;
        ListNode pointer2 = list2;

        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;

        while(pointer1 != null || pointer2 != null){

                if(pointer1 == null || pointer2 != null &&  pointer1.val > pointer2.val){
                    cur.next = new ListNode(pointer2.val);
                    pointer2 = pointer2.next;
                } 
                else{
                    cur.next = new ListNode(pointer1.val);
                    pointer1 = pointer1.next;
                } 
           
            cur = cur.next;
        }

        return dummy.next;
        
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant