删除链表中的元素

2017-09-21  本文已影响0人  zhujiaqqq

描述

删除链表中等于给定值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 null;
            }
            while (head.val == val) {
                if (head.next != null) {
                    head = head.next;
                } else {
                    return null;
                } 
            }
            ListNode tmp = head;
            ListNode tmpNext = tmp.next;
            while (tmpNext != null) {
                if (tmpNext.val != val) {
                    tmp = tmpNext;
                    tmpNext = tmp.next;
                } else {
                    tmp.next = tmpNext.next;
                    tmpNext = tmp.next;
                }
            }
            return head;
        }
}

请关注我的个人网站:https://zhujiaqqq.github.io/

上一篇 下一篇

猜你喜欢

热点阅读