题解 | #删除链表峰值#
删除链表峰值
https://www.nowcoder.com/practice/30a06e4e4aa549198d85deef1bab6d25
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteNodes(ListNode* head) {
// 单元素没有next,直接返回
if (head->next == nullptr) {
return head;
}
// 设置前节点的指针,并将现指针后移
ListNode* cur = head;
ListNode* pre = cur;
cur = cur->next;
// 现指针的下一节点非空的情况下,满足条件则删除,否则pre与cur均移动
while(cur->next != nullptr){
if(cur->val>pre->val && cur->val>cur->next->val){
pre->next=cur->next;
cur=cur->next;
}
else {
pre=pre->next;
cur=cur->next;
}
}
return head;;
}
};