[LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 兩個有序鏈表合併爲一個&刪除鏈表重複元素

[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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章