✨hello,进来的小伙伴们,你们好耶!✨
🎁🎁系列专栏:【牛客刷题】
🍯🍯作者简介:一名双非本科大三在读的Java编程小白,我很平凡,学会努力!
🍬🍬给大家推荐一个超级好用的刷题网站——牛客网!
点击链接注册,开启刷题之路!
问题描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路非常简单,就是两个引用对应的值相互比较,谁小谁先进去,然后cur = cur.next,S1=S1.next往后走,不满足的话就S2 = S2.next,直到某个链表被遍历完,最后返回头结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode S1, ListNode S2) {
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while (S1 != null && S2 != null) {
if (S1.val < S2.val) {
cur.next = S1;
cur = cur.next;
S1 = S1.next;
} else {
cur.next = S2;
cur = cur.next;
S2 = S2.next;
}
}
if (S1 == null) {
cur.next = S2;
} else {
cur.next = S1;
}
return dummyHead.next;
}
}
版权归原作者 辰柒_ 所有, 如有侵权,请联系我们删除。