[LeetCode-interview algorithm classic-Java implementation] [021-Merge Two Sorted Lists (Merge Two Sorted Single-Chain tables)], leetcode -- java
[021-Merge Two Sorted Lists )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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.
Theme
Merge two sort linked lists and return a new list. The result of the new linked list is composed of two original linked list nodes, that is, the merged linked list cannot contain the newly created node.
Solutions
Use the header node root for auxiliary operations, create a header node, and then use two references to point to the header nodes of two linked lists, and remove the nodes with smaller node values to the end of the root linked list, at the same time, the referenced chain header is moved to the next node, and the operation continues until one of the original two linked lists is empty, and the remaining nodes are connected to the end of the root linked list. Finally, the next node of root is returned, which is the new linked list header.
Code Implementation
Linked List Node Type
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; }}
Algorithm Implementation class
Public class Solution {public ListNode mergeTwoLists (ListNode l1, ListNode l2) {ListNode head = new ListNode (0); // create a header node and delete ListNode tail = head; while (l1! = Null & l2! = Null) {if (l1.val <= l2.val) {tail. next = l1; l1 = l1.next;} else {tail. next = l2; l2 = l2.next;} tail = tail. next; // move to the new tail node} tail. next = (l1! = Null? L1: l2); return head. next; // The next node of the head is the first data node }}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47016121]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.