码迷,mamicode.com
首页 > 其他好文 > 详细

21. Merge Two Sorted Lists

时间:2018-03-10 17:00:29      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:uri   语言   pos   str   problem   int   ati   merge   就是   

原题链接:https://leetcode.com/problems/merge-two-sorted-lists/description/
这道题目是合并两个有序的单链表。。。尼玛,这不就是《数据结构(C语言版)》上的原题嘛,并不是考察什么高超的算法,就是普通的链表操作知识而已!

import java.util.Stack;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(3);
        l1.next.next = new ListNode(5);
        l1.next.next.next = new ListNode(8);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(2);
        l2.next.next = new ListNode(3);
        l2.next.next.next = new ListNode(6);

        ListNode res = s.mergeTwoLists(l1, l2);
        System.out.println(res);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode root = new ListNode(0);
        ListNode temp = root;

        ListNode m = l1;
        ListNode n = l2;

        while (m != null && n != null) {
            if (m.val > n.val) {
                temp.next = n;
                n = n.next;

            } else {
                temp.next = m;
                m = m.next;
            }
            temp = temp.next;
        }

        if (m != null) { // so n is null
            temp.next = m;
        }
        if (n != null) { // so m is null
            temp.next = n;
        }

        return root.next;
    }

}

21. Merge Two Sorted Lists

标签:uri   语言   pos   str   problem   int   ati   merge   就是   

原文地址:https://www.cnblogs.com/optor/p/8540620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!