版权声明:个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢! 转载请注明出处 谢谢合作 https://blog.csdn.net/qq_43377749/article/details/88692044
合并两个已排序的链接列表并将其作为新列表返回。新列表应该通过拼接前两个列表的节点来完成。
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.
例子:
输入: 1-> 2-> 4,1-> 3-> 4
输出: 1-> 1-> 2-> 3-> 4-> 4
解析:
- 先判空,空的话放回另一个即可
- 都不空的情况下,把第二个连接到第一个后边去(注意记录最后链表的长度)
- 裁员冒泡排序即可
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newlist = l1;
int num = 0;
if ( l1 == null ) {
return l2;
}else if ( l2 == null ) {
return l1;
}
while ( newlist.next != null ) {
newlist = newlist.next;
num++ ;
}
while ( l2 != null ) {
newlist.next = l2;
l2 = l2.next;
newlist = newlist.next;
num++ ;
}
for (int i = 0; i < num; i++) {
newlist = l1;
while( newlist.next != null ) {
if ( newlist.next.val < newlist.val ) {
int box = newlist.val;
newlist.val = newlist.next.val;
newlist.next.val = box;
}
newlist = newlist.next;
}
}
return l1;
}
}
希望我的回答对您有帮助~~