习惯了用C语言,在java中对链表的运用还是不太熟练。因为题目中给的两个链表都是非递减顺序,所以直接比较就行了,创建一个新的链,小的放进去,最后再把剩下的接上。代码:
/**
* 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 p, ListNode q) {
ListNode head = new ListNode ();
ListNode s = head;
while ((p!=null)&(q!=null)) {
if (p.val < q.val) {
s.next = new ListNode(p.val);
p = p.next;
}
else {
s.next = new ListNode(q.val);
q = q.next;
}
s = s.next;
}
if (p == null) {
s.next = q;
}
else {
s.next = p;
}
return head.next;
}
}