LintCode_452_删除链表中的元素

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 18:54   747   0

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

样例

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @param val an integer
     * @return a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        // Write your code here
        if(head == null){
            return head;
        }
        ListNode cur = head;
        ListNode nex = head.next;
        while (nex != null){
            if(nex.val == val){
                cur.next = nex.next;
                nex = nex.next;
            }else{
                cur = cur.next;
                nex = nex.next;
            }
        }
        if(head.val == val) head = head.next;
        return head;
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP