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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
题意:
合并两个已排序的链表并将其作为新链表返回。新链表应该通过拼接前两个链表的节点来完成。例如:
链表L1包含三个节点,为1,2,4
链表L2包含三个节点,为1,3,4
将L1和L2合并后的新链表包含6个节点,为1,1,2,3,4,4
分析:
先来看段代码,下面是定义的ListNode类,有两个属性,一个是存储整数值的val,一个是ListNode类本身的next,存储下一个ListNode的地址值(指针)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
因为给的链表都是已经排过序的(由小到大),只需要依次比较两个链表的元素val值即可,并且存入一个新的链表里面。如果某一个链表先循环完,新链表剩下的元素就是另外一个链表剩下的元素。
public Node mergeTwoSortedList1(Node node1, Node node2) {
Node res = new Node(-1);
Node cur = res;
while (null != node1 && null != node2) {
if (node1.val <= node2.val) {
cur.next = node1;
node1 = node1.next;
} else {
cur.next = node2;
node2 = node2.next;
}
cur = cur.next;
}
cur.next = (null == node1) ? node2 : node1;
return res.next;
}
循环判断再取值的情况,很容易联想到递归,即自己调用自己,同时给予退出条件即可。使用递归的好处就是代码量少。
public Node mergeTwoSortedList(Node node1, Node node2) {
if (null == node1) {
return node2;
}
if (null == node2) {
return node1;
}
if (node1.val <= node2.val) {
node1.next = mergeTwoSortedList(node1.next, node2);
return node1;
} else {
node2.next = mergeTwoSortedList(node1, node2.next);
return node2;
}
}
此题解法远不止上面这两种,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流。