leetcode203移除链表元素

leetcode 203 Remove Linked List Elements

Posted by BY on July 15, 2020

前言

持续更新了

正文

问题来源

本问题来自leetcode上的203题。(最近有点累,刷个水题吧)

问题描述

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

示例 1:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

分析:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeElements(head *ListNode, val int) *ListNode {
    h := &ListNode{0, head}
    p := h 
    for p!=nil && p.Next != nil {
        if p.Next.Val == val {
            p.Next = p.Next.Next
            continue
        }
        p = p.Next
    }
    return h.Next
}

官方解答

class Solution {
  public ListNode removeElements(ListNode head, int val) {
    ListNode sentinel = new ListNode(0);
    sentinel.next = head;

    ListNode prev = sentinel, curr = head;
    while (curr != null) {
      if (curr.val == val) prev.next = curr.next;
      else prev = curr;
      curr = curr.next;
    }
    return sentinel.next;
  }
}

总结:

勤思考。

结语

不管怎么样好好加油。