题目描述:
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
题解:
/**
* 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; //去除头部重复元素
}
if(head == null)
return head;
ListNode pre=head;
ListNode cur=head.next;
while(cur!=null){
if(cur.val == val){
pre.next=cur.next; //删除重复元素
cur=cur.next; //cur结点往后移
}else{
cur=cur.next;
pre=pre.next;
}
}
pre=head; //pre结点重新指向头结点
return pre;
}
}