美文网首页
LeetCode 203 Remove Linked List

LeetCode 203 Remove Linked List

作者: ShuiLocked | 来源:发表于2016-08-02 10:01 被阅读122次

LeetCode 203 Remove Linked List Elements

====================================

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

对于链表的删除添加,一定要注意头节点的操作,需要与其它节点分开处理。引入setinel作为伪头节点,可以避免分开处理简化代码。

对于删除添加操作,一般的思路都是:
定义curr指针指向当前结点,pre指针指向curr的上一个节点。本题可以用类似思路,遍历所有节点,同时保留每个节点的上一个节点,当遇到节点值是val时,删除该节点。

代码:

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode setinel = new ListNode(0);
        setinel.next = head;
        ListNode pre = setinel;
        ListNode curr = setinel.next;
        
        while (curr != null) {
            if (curr.val == val) {
                pre.next = curr.next;
            } else {
                pre = curr;
            }
            curr = curr.next;
        }
        return setinel.next;
    }
}

本题还可以直接先将从头部开始的val值得节点去除,这样就不需要考虑头节点的特殊情况,也就不需要额外的伪头节点了。

while (head != null && head.val == val) {
   head = head.next;
}

相关文章

网友评论

      本文标题:LeetCode 203 Remove Linked List

      本文链接:https://www.haomeiwen.com/subject/jiefsttx.html