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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值