LeetCode -- 删除链表中值为k的元素

来源:互联网 发布:淘宝千人千面在哪设置 编辑:程序博客网 时间:2024/06/07 12:34
本题目比较直接,一次遍历遇到匹配的元素直接删除(通过n.next = n.next.next)就可以了,只是需要考虑到:
1.首节点的情况
2.末节点的情况


以下为实现:

public ListNode RemoveElements(ListNode head, int val) {        // null listif(head == null){return null;}// constains only one nodeif(head.next == null && head.val == val){return null;}//remove first nodeswhile(head.val == val){    if(head.next == null){        break;    }head = head.next;}var tmp = head;// nodes in betweenwhile(head.next != null){if(head.next.val == val){head.next = head.next.next;}else{head = head.next;}if(head.next == null){break;}}// last nodeif(head.val == val){return null;}// restore head nodehead = tmp;return head;    }


0 0
原创粉丝点击