categories: [Blog,Algorithm]


203. 移除链表元素

难度简单540
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5.

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode removeElements(ListNode head, int val) {
  13. ListNode sentinal=new ListNode(0);
  14. sentinal.next=head;
  15. ListNode cur=head;
  16. ListNode pre=sentinal;
  17. while(cur!=null){
  18. if(cur.val==val){
  19. pre.next=cur.next;
  20. }else{
  21. pre=cur;
  22. }
  23. cur=cur.next;
  24. }
  25. return sentinal.next;
  26. }
  27. }