203. 删除链表中的节点(Remove Linked List Elements) - Leetcode简单题解

203. 删除链表中的节点

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

思路:

先处理head节点,因为此题head节点也存在数据
在继续处理后续的其他节点
这里使用了前驱节点进行删除的辅助操作

详见代码
class Solution_203 {
    public ListNode removeElements(ListNode head, int val) {
        //先找头节点问题,很另类,这个题头节点也有值
        //如果头节点的值是需要删除的值,那么就一直后移
        while (head != null && head.val == val) {
            head = head.next;
        }
        //判断链表是不是为空
        if (head == null) return null;
        //这里假设这个节点是要删除节点的前一个节点(前驱节点),方便删除
        ListNode tmp = head;
        while (tmp.next != null) {//判断后一节点是否存在
            if (tmp.next.val == val) {
                tmp.next = tmp.next.next; //删除操作 tmp.next 指向 下下个节点, 完成删除
            } else { // 关键: 如果进行了删除操作,则后一个节点更新了,所以前驱节点不需要移动,否则前驱节点向后移动
                tmp = tmp.next;
            }
            if (tmp == null) return head; //前驱移动,判空

        }
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这道题目需要我们实现一个循环链表,并在其删除指定位置的节点。具体实现可以分为以下几个步骤: 1. 定义循环链表节点结构体,包括数据域和指向下一个节点的指针域。 2. 定义循环链表的头节点,并初始化为空。 3. 读入输入的数据,将其插入到循环链表的尾部。 4. 遍历循环链表,找到需要删除节点的前一个节点。 5. 将需要删除节点链表摘除,并释放其内存空间。 6. 遍历循环链表,输出剩余节点的数据。 下面是具体的代码实现: ``` #include <iostream> using namespace std; // 定义循环链表节点结构体 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; int main() { // 定义循环链表的头节点 ListNode* head = NULL; // 读入输入的数据,将其插入到循环链表的尾部 int num; while (cin >> num && num != 0) { ListNode* node = new ListNode(num); if (head == NULL) { head = node; head->next = head; } else { ListNode* cur = head; while (cur->next != head) { cur = cur->next; } cur->next = node; node->next = head; } } // 遍历循环链表,找到需要删除节点的前一个节点 ListNode* pre = head; while (pre->next != head) { pre = pre->next; } // 将需要删除节点链表摘除,并释放其内存空间 ListNode* cur = head; while (cur->next != head) { if (cur->val % 2 == 0) { pre->next = cur->next; ListNode* temp = cur; cur = cur->next; delete temp; } else { pre = cur; cur = cur->next; } } if (cur->val % 2 == 0) { pre->next = cur->next; delete cur; } // 遍历循环链表,输出剩余节点的数据 cur = head; while (cur->next != head) { cout << cur->val << "\t"; cur = cur->next; } cout << cur->val << endl; return 0; } --相关问题--:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值