题目描述: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
解题思路:由于存在重复值的节点,所以需要考虑每次是否是正指向元素等于需删除节点。
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode p,q;
while(head!=null&&head.val==val) head=head.next;
p=q=head;
while(p!=null){
if(p.next==null) return head;
q=p;
if(p.next.val==val) q.next=p.next.next;
p=q.next;
while(p!=null&&p.val==val) {
q.next=p.next;
p=q.next;
}
}
return head;
}
}
原题题目:
https://leetcode.com/problems/remove-linked-list-elements/