删除链表中的元素


删除链表中等于给定值val的所有节点。

样例

给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5



1
/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param head a ListNode 12 * @param val an integer 13 * @return a ListNode 14 */ 15 public ListNode removeElements(ListNode head, int val) { 16 // Write your code here 17 if (null == head) 18 return head; 19 20 ListNode p = head; 21 ListNode pre = null; 22 23 while (null != p) { 24 if (p.val == val) { 25 ListNode del = p; 26 p = p.next; 27 if (null != pre) { 28 pre.next = p; 29 } else { 30 head = p; 31 } 32 33 } else { 34 pre = p; 35 p = p.next; 36 } 37 } 38 39 return head; 40 41 } 42 }
原文地址:https://www.cnblogs.com/qingyuuu/p/5885560.html