[1] Merge Two Sorted Lists
虽然题目简单,但是个人认为代码写的还是很好看的!
本题的关键在于给定的两个链表并没有说明是递增还是递减排序的!虽然LEETCODE中忽略了这一点,但是我觉得还是需要判断的
在条件分支中异或语句,给出了对于递增递减的选择!
if(!l1||!l2)
return l1?l1:l2;
bool increase,judge;
ListNode *head=new ListNode(0);
ListNode *stick=head;
ListNode *a=l1,*b=l2;
//judge if the tow lists are increase
while(a->next&&a->next->val!=l1->val)
a=a->next;
while(b->next&&b->next->val!=l2->val)
b=b->next;
increase=(l1->val<=a->val)&&(l2->val<=b->val);
//now stick
while(l1&&l2)
{
judge=(l1->val>=l2->val)^increase;
stick->next=judge?l1:l2;
judge?l1=l1->next:l2=l2->next;
stick=stick->next;
}
stick->next=(l1?l1:l2);
//return head->next;
stick=head->next;
delete(head);head=NULL;
return stick;
[2] Remove Duplicates from Sorted List
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(!head)
return head;
ListNode *headrecord=head;
while(head->next)
{
if(head->val==head->next->val)
{
ListNode *record=head->next->next;
delete(head->next);
head->next=record;
}
else
head=head->next;
}
return headrecord;
}
};