剑指 Offer 25. 合并两个排序的链表 - 力扣(LeetCode) (leetcode-cn.com)
目录
基本方法
运行结果
代码
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* preHead = new ListNode(NULL), * iter = preHead;
while (l1 && l2) {
l1->val < l2->val ?
(iter->next = l1, l1 = l1->next) : (iter->next = l2, l2 = l2->next);
iter = iter->next;
}
iter->next = l1 ? l1 : l2;
return preHead->next;
}
};
面向对象方法(手痒痒了……
起初只是感觉基本方法中的条件表达式太长,想要缩短一下,打算把 "iter->next = l" 和 "l = l->next"这两条语句封装在一起,把条件表达式改成 "iter->next = <bool expression> ? _ : _"的形式。这样的话需要封装 "l = l->next" 的函数的返回值是 "l",这不就相当于自增运算符了嘛!直接重载一下自增操作符就好了。但是一动手,发现操作符重载只能在特定的类中,只有某一类的对象才能使用该类中重载后的操作符,那干脆把 "ListNode*" 封装成一个类得了。于是就有了连锁反应……
运行结果(有点拉跨……
代码
class lst {
ListNode* p;
const ListNode* preHead;
public:
lst() :p(new ListNode(0)), preHead(p) {}
lst(ListNode* l) :p(l), preHead(NULL) {}
ListNode* head() const {
return preHead->next;
}
void operator++() {
p = p->next;
}
lst operator++(int k) {
ListNode* tmp = p;
p = p->next;
return tmp;
}
bool not_empty() {
return p != NULL;
}
int _val() const {
return p->val;
}
ListNode* ptr() const {
return p;
}
void add(const lst L) {
p->next = L.ptr();
}
bool compare(const lst& L) const {
return this->_val() > L._val();
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
lst L1(l1), L2(l2), iter;
while (L1.not_empty() && L2.not_empty()) {
iter.add(L2.compare(L1) ? L1++ : L2++);
++iter;
}
iter.add(L1.not_empty() ? L1 : L2);
return iter.head();
}
};