[Leetcode]203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

 

思路:我们看当前节点的下一个是否等于val,如果等于的话,就把当前节点的next指向下个节点的next

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode removeElements(ListNode head, int val) {
11         ListNode current = head;
12         while (current!=null){
13             if (current==head&&current.val==val){
14                 head = head.next;     //如果是头节点的话,就移动头节点
15                 current = head;
16             }
17             else if (current.next!=null&&current.next.val==val)
18                 current.next = current.next.next;  //看当前节点的下一个的值是否为val
19             else
20                 current = current.next;
21         }
22     }
23 }

 

转载于:https://www.cnblogs.com/David-Lin/p/7768667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值