美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: namelessEcho | 来源:发表于2017-09-28 17:18 被阅读0次

    插入表二的值到表一中去以后,要将比较的值也变成这个插入的值

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode pos1 = l1;
            ListNode pos2 = l2;
            ListNode dummy = new ListNode (0);
            dummy.next=l1;
            ListNode pre = dummy;
            while(pos1!=null&&pos2!=null)
            {
                while(pos1!=null&&pos1.val<=pos2.val)
                {
                    pos1=pos1.next;
                    pre=pre.next;
                }
                if(pos1==null)break;
                // first pos1.val>pos2.val insert pos2 before pos1 ;
               ListNode temp = pos2.next;
               pre.next=pos2;
               pos2.next=pos1;
                // now pos1 is the inset val ,so change pos1 
               pos2=temp;
               pos1=pre.next;
            }
            if(pos1==null)
            {
                pre.next=pos2;
            }
            return dummy.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:21. Merge Two Sorted Lists

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