题目描述:
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val){
head = head.next;//先找到第一个值不为val的结点
}
if(head == null){
return head;//如果都为val,直接返回空的头结点
}
ListNode pre = head;//定义一个pre结点来进行移除操作
while(pre.next != null){
if(pre.next.val == val){
pre.next = pre.next.next;
}
else pre = pre.next;
}
return head;
}
}