【Leetcode】203. Remove Linked List Elements

来源:互联网 发布:关晓彤马思纯关系 知乎 编辑:程序博客网 时间:2024/05/21 06:13

思路:

(1)若链表为空,则返回null。

(2)遍历整个链表,cur指向当前判断的节点,pre指向其前驱结点。

(3)若cur的值等于指定值,若cur指向的是头结点,则head指向cur的下一节点,pre指向cur;否则,pre的next指向cur的next。

(4)cur指向下一节点。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {        if (head == null)            return null;        ListNode pre = null, cur = head;        while (cur != null) {            if (cur.val == val) {                if (cur == head) {                    head = cur.next;                    pre = cur;                }                else                     pre.next = cur.next;            }            else                pre = cur;            cur = cur.next;        }        return head;    }}
Runtime:2ms

1 0
原创粉丝点击