
需求:删除链表中等于给定值val的所有节点。
样例
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
直观方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public ListNode removeElements(ListNode head, int val) { if(head == null) return head; ListNode cur = head,next = head.next; while(next != null){ if(next.val == val){ cur.next = next.next; next = next.next; }else{ cur = cur.next; next = next.next; } } //最后去除表头 if(head.val == val) head = head.next; return head; }
|
近期评论