例如:
输入:
链表1: 1->3->5->7
链表2: 2->4->6->8
输出:
链表交集: 1->2->3->4->5->6->7->8
a = input().split('->') b = input().split('->') c = a+b c.sort() for i in c: if i == c[-1]: print(i) else: print(i+'->',end='')python
public static ListNode Merge(ListNode list1,ListNode list2){
if(list1 == null && list2 == null){
return null;
}
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
ListNode head = null;
ListNode cur = null;
while(list1 != null && list2 != null){
if(list1.val <= list2.val){
if(head == null){
head = list1;
cur = head;
list1 = list1.next;
}else{
cur.next = list1;
cur = list1;
list1 = list1.next;
}
}else{
if(head == null){
head = list2;
cur = head;
list2 = list2.next;
}else{
cur.next = list2;
cur = cur.next;
list2 = list2.next;
}
}
}
if(list1 != null){
cur.next = list1;
}
if(list2 != null){
cur.next = list2;
}
return head;
}
public: { ListNode * sortwo(ListNode *A, ListNode *B){ ListNode * temp1=NULL,temp2=NULL,temp=NULL; ListNode * res; if(!A&&!B) return NULL; if(!A && B) return B; if(A&& !B) return A; if(A->val >= B->val) {res=A; temp1=B->next;temp=B;temp2=A->next;} else{res=B; temp1=A->next;temp=A,temp2=B->next;} while(A&&B) { //temp1=temp1->next; if(temp->val>=temp1->val) { if(temp->val<=temp1->val) { res->next=temp; res->next->next=temp1; temp=temp2; temp2=temp2->next; } else { } temp1=temp1->next; } } };