删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
分析:
用一个指针指向当前判断节点的前一个节点,如果val相等则删除
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *ancestor = new ListNode(0);
ancestor->next = head;
ListNode *pre = ancestor;
ListNode *curr = head;
while(curr){
// val相等删除
if(curr->val == val){
pre->next = curr->next;
curr = pre->next;
}else{
pre = pre->next;
curr = curr->next;
}
}
return ancestor->next;
}
};
本文介绍了一种从链表中删除所有等于给定值节点的方法。通过使用一个祖先节点和两个指针进行遍历,当遇到目标值时,通过调整指针连接跳过该节点,从而实现删除操作。
1025

被折叠的 条评论
为什么被折叠?



