Merge two sorted linked lists and return it as a new list. The new list shoshould be made by splicing together the nodes of the first two lists.
Description:
Similar to the input two linked lists in C language, connect them in order.
But this time I tried to use Java, and the idea was the same.
Code:
/*** 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 head; If (L1 = NULL) // determine whether a string is an empty string return L2; else if (L2 = NULL) return L1; If (l1.val <l2.val) {// determine the first node head = L1; l1 = l1.next;} else {head = L2; L2 = l2.next;} l Istnode temp = head; while (L1! = NULL & L2! = NULL) {If (l1.val <l2.val) // compare each node {temp. next = L1; temp = temp. next; L1 = l1.next;} else {temp. next = L2; temp = temp. next; L2 = l2.next; }}if (L1 = NULL) // end a string and directly connect it to another temp. next = L2; else temp. next = L1; return head ;}}
Leetcode merge two sorted lists