Day19——T83. 删除排序链表中的重复元素、AcwingT84.求1 + 2 + … + n
T83. 删除排序链表中的重复元素
给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
-
双指针
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == nullptr) return head; ListNode* p = head, *q = p->next; while(q) { if(p->val == q->val) { q = q->next; p->next = q; } else { p = q; q = q->next; } } return head; } };
-
单指针
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (!head) { return head; } ListNode* cur = head; while (cur->next) { if (cur->val == cur->next->val) { cur->next = cur->next->next; } else { cur = cur->next; } } return head; } };
AcwingT84
求1 + 2 + … + n,不能用乘除法,for,while,if,else,switch,case等关键字以及条件判断句(A?B:C)
class Solution {
public:
int getSum(int n)
{
int res = n;
n > 0 && (res += getSum(n -1));//利用短路运算终止递归
return res;
}
}