zoukankan      html  css  js  c++  java
  • 【JAVA、C++】LeetCode 021 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.
    解题思路:
    新建一个ListNode进行存储即可,JAVA实现如下:
    	static public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    		ListNode listnode=new ListNode(0);
    		ListNode index=listnode;
    		while(l1!=null&&l2!=null){
    			if(l1.val>l2.val){
    				ListNode temp=l1;
    				l1=l2;
    				l2=temp;
    			}
    			index.next=new ListNode(l1.val);
    			index=index.next;
    			l1=l1.next;
    		}
    		if(l1==null)
    			index.next=l2;
    		else 
    			index.next=l1;
    		return listnode.next;
    	}
    

     C++:

     1 class Solution {
     2  public:
     3      ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
     4          if (l1 == NULL)
     5              return l2;
     6          else if (l2 == NULL)
     7              return l1;
     8          ListNode* start;
     9          if (l1->val < l2->val) {
    10              start = l1;
    11              l1 = l1->next;
    12          }
    13          else {
    14              start = l2;
    15              l2 = l2->next;
    16          }
    17          ListNode* cur = start;
    18          while (l1 != NULL&&l2 != NULL) {
    19              if (l1->val < l2->val) {
    20                  cur->next = l1;
    21                  cur = cur->next;
    22                  l1 = l1->next;
    23              }
    24              else {
    25                  cur->next = l2;
    26                  cur = cur->next;
    27                  l2 = l2->next;
    28              }
    29          }
    30          if (l1 == NULL)
    31              cur->next = l2;
    32          else
    33              cur->next = l1;
    34          return start;
    35      }
    36  };
  • 相关阅读:
    jstack 分析程序性能
    网关-zuul介绍 第一篇 网关解决的问题
    通过Fegin远程调用 ,返回JPA Page 对象报错
    css自定义字体
    CSS3选择器
    表格操作
    商品筛选条件
    多级菜单
    一排元素往下掉
    控制提示框不溢出父级盒子
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4473537.html
Copyright © 2011-2022 走看看