zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    个人思路:用两个指针分别记录两个链表,每次比较指针对应节点大小将较小的断链,当有一个链表为空则将另一个链表接到后面即可。

     1 /*
     2 public class ListNode {
     3     int val;
     4     ListNode next = null;
     5 
     6     ListNode(int val) {
     7         this.val = val;
     8     }
     9 }*/
    10 public class Solution {
    11     public ListNode Merge(ListNode list1,ListNode list2) {
    12         if(list1==null)
    13             return list2;
    14         else if(list2==null)
    15             return list1;
    16         else{
    17             ListNode temp = null;
    18             if(list1.val<list2.val){
    19                 temp = list1;
    20                 list1 = list1.next;
    21                 }else{
    22                 temp = list2;
    23                 list2 = list2.next;
    24             }
    25             ListNode r = temp;
    26             while(list1!=null&&list2!=null){
    27                 if(list1.val<list2.val){
    28                     temp.next = list1;
    29                     list1 = list1.next;
    30                     temp = temp.next;
    31                 }else{
    32                     temp.next = list2;
    33                     list2 = list2.next;
    34                     temp = temp.next;
    35                 }
    36             }
    37             if(list1==null){
    38                 temp.next = list2;
    39             }else{
    40                 temp.next = list1;
    41             }
    42             return r;
    43         }
    44         
    45     }
    46 }
  • 相关阅读:
    java小知识点5
    java小知识点4
    java小知识点3
    编程之法:面试和算法心得(寻找最小的k个数)
    389. Find the Difference
    104. Maximum Depth of Binary Tree
    485. Max Consecutive Ones
    693. Binary Number with Alternating Bits
    463. Island Perimeter
    566. Reshape the Matrix
  • 原文地址:https://www.cnblogs.com/haq123/p/12154810.html
Copyright © 2011-2022 走看看