Merge Two Sorted Lists

来源:互联网 发布:软件 开发 编辑:程序博客网 时间:2024/06/17 13:56
https://oj.leetcode.com/problems/merge-two-sorted-lists/

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题意:把两个有序的链表合并成一个有序链表

思路:归并排序的归并部分,两个指针指向链表的头节点,比较元素大小,把小的先加入结果链表,并且该指针后移。如果其中一个链表到达尾部,则将另一个链表的剩余部分复制到结果链表

实现:
/** * Definition for singly - linked list. * public class ListNode { *     int val ; *     ListNode next; *     ListNode( int x) { *         val = x; *         next = null; *     } * } */public class Solution {      public ListNode mergeTwoLists(ListNode l1, ListNode l2 ) {           ListNode first= new ListNode(0);//结果链表           ListNode l= first;           while (l1 != null|| l2!= null){                             ListNode t= new ListNode(0);               if (l1 == null){ //如果l1链表到结尾,则把另一个链表以此复制到结果链表                    t.val= l2.val;                    l2= l2.next;              }               else if (l2 == null){ //如果l2链表到结尾,则把另一个链表以此复制到结果链表                    t.val= l1.val;                    l1= l1.next;              }               else if (l1 .val<l2 .val){//把两个指针对应的值小的元素的节点加入结果链表                    t.val= l1.val;                    l1= l1.next;              }               else { //把两个指针对应的值小的元素的节点加入结果链表                    t.val= l2.val;                    l2= l2.next;              }               l.next= t;               l= t;          }           return first .next;     }}


0 0
原创粉丝点击