LeetCode 203. Remove Linked List Elements (移除链表中的项)

2023-04-20,,

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


题目标签:Linked List

  题目给了我们一个 链表 和一个 val,让我们把链表中 等于 val 的点都去除。

  情况1: 如果head.val == val,那么设 head = head.next,同时cursor 也要重新设定。

  情况2: 如果cursor.next.val == val 那么把cursor 连到 下下个点,跳过中间点。

  情况3: 如果cursor.next.val != val 的话,那么移动cursor 去下一个点。

Java Solution:

Runtime beats 50.37%

完成日期:06/10/2017

关键词:singly-linked list

关键点:检查cursor.next.val

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution
{
public ListNode removeElements(ListNode head, int val)
{
ListNode cursor = head; while(cursor != null)
{
if(head.val == val)
{
head = head.next;
cursor = head;
}
else if(cursor.next != null && cursor.next.val == val)
{
ListNode valNode = cursor.next;
cursor.next = valNode.next;
valNode.next = null;
}
else
cursor = cursor.next; } return head;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

LeetCode 203. Remove Linked List Elements (移除链表中的项)的相关教程结束。

《LeetCode 203. Remove Linked List Elements (移除链表中的项).doc》

下载本文的Word格式文档,以方便收藏与打印。