比较简单,自己搞定
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.
分析: 和merge sort 里的方法一样
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
tra,trb = l1,l2
trc = ListNode(1000)
prehead = trc
while True:
if tra==None:
trc.next = trb
return prehead.next
if trb==None:
trc.next = tra
return prehead.next
if tra.val<=trb.val:
trc.next = tra
tra = tra.next
else:
trc.next = trb
trb = trb.next
trc = trc.next
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *tra, *trb, *prehead;
tra = l1;
trb = l2;
ListNode *trc = new ListNode(100);
prehead = trc;
while (true){
if (tra==NULL){
trc->next = trb;
return prehead->next;
}
if (trb==NULL){
trc->next = tra;
return prehead->next;
}
if (tra->val<=trb->val){
trc->next = tra;
trc = tra;
tra = tra->next;
}
else{
trc->next = trb;
trc = trb;
trb = trb->next;
}
}
}
};
语法总结:
1. python里时 True, C++ 里是true
2. C++指针时, 最好这么写ListNode *p1,*p2; ListNode *p3 = new ListNode(10);