题目描述:
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—cur.next = cur.next.next
不是的话–cur = cur.next;
在这里需要新增一个节点(首结点等于val的情况)–可能为空
代码:
/**
* 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) {
if(head==null)
return null;
ListNode newNode = new ListNode(0);
newNode.next = head;
ListNode cur = newNode;
while(cur.next!=null){
if(cur.next.val==val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
//返回值比较重要
return newNode.next;
}
}