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  };
  • 相关阅读:
    JPA
    XMPP技术之Smack库的自定义消息扩展
    VMVare的窗口自适应
    linux c tcp p2p
    linux 消息队列
    基数排序-LSD
    基数排序-纪念欧某新
    归并排序
    锦标赛排序
    快速排序 之添加复合插入排序和原始序列取中值左pivot
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4473537.html
Copyright © 2011-2022 走看看