leecode 203. 移除链表元素

/**
 * Created by zhanghaipeng on 2019/8/6.
 * 删除链表中等于给定值 val 的所有节点。
 * leecode 203. 移除链表元素
 * 示例:
 * 输入: 1->2->6->3->4->5->6, val = 6
 * 输出: 1->2->3->4->5
 */
public class removeElementsLink {

    public ListNode removeElements(ListNode head, int val) {
        ListNode res = new ListNode (-1);
        res.next = head;

        ListNode pre = res;
        ListNode cur =  null;
        if(head == null){
            return null;
        }else{
            cur = head;
        }

        while(cur != null){
            if(cur.val == val){
                pre.next = cur.next;
                cur = cur.next;
            }else {
                pre = cur;
                cur = cur.next;
            }
        }

        return res.next;
    }

    public static void main(String[] args){
        ListNode head = new ListNode (0);
        ListNode n1 = new ListNode (1);
        ListNode n2 = new ListNode (2);
        ListNode n3 = new ListNode (3);
        ListNode n4 = new ListNode (4);
        ListNode n5 = new ListNode (5);
        ListNode n6 = new ListNode (6);
        head.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        ListNode node = new removeElementsLink ().removeElements (head,2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是移除链表元素的Python代码: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def removeElements(head: ListNode, val: int) -> ListNode: # 处理头部节点为要删除元素的情况 while head is not None and head.val == val: head = head.next # 处理链表中间节点为要删除元素的情况 if head is not None: node = head while node.next is not None: if node.next.val == val: node.next = node.next.next else: node = node.next return head ``` 这里定义了一个ListNode类表示链表节点,其中val表示节点的值,next表示指向下一个节点的指针。removeElements函数的第一个参数head表示链表的头节点,第二个参数val表示要删除的元素值。函数的返回值是移除后的链表头节点。 函数的实现分为两步: 1. 处理头部节点为要删除元素的情况,即如果头部节点的值等于要删除的元素值,则将头部节点指向下一个节点,直到头部节点的值不等于要删除的元素值。 2. 处理链表中间节点为要删除元素的情况,即从头节点开始遍历链表,如果当前节点的下一个节点的值等于要删除的元素值,则将当前节点的next指针指向下一个节点的next指针,即跳过当前节点的下一个节点;否则,将当前节点指向下一个节点。遍历完成后,返回链表的头节点。 注意,这里的实现并没有考虑链表为空的情况,需要在调用函数前进行判断。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值