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
题意:删除链表中的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
//////head指向的就是第一个数据节点。并没有在数据前另外申请
public ListNode removeElements(ListNode head, int val) {
ListNode cur=head;
ListNode newhead=new ListNode(1);
newhead.next=head;
ListNode pre=newhead;
// pre.next=head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
}else{
pre=pre.next;
}
cur=cur.next;
}
// System.out.println(head.val);
return newhead.next;
}
}
PS:防止头被删除,new一个head指向原来的head。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。有点恶心
转载于:https://blog.51cto.com/fulin0532/1905456