yinda_peng 发表于 2023-7-19 15:06:33

LeetCode-203

本帖最后由 yinda_peng 于 2023-7-19 15:08 编辑

203. Remove Linked List Elements    (easy)

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.


Example 1:
Input: head = , val = 6
Output:
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = , val = 7
Output: []


My Code:
/**
* Definition for singly-linked list.
* struct ListNode {
*   int val;
*   struct ListNode *next;
* };
*/


struct ListNode* removeElements(struct ListNode* head, int val){
    struct ListNode* Head = malloc(sizeof(struct ListNode));
    Head->next = head;
    struct ListNode* temp = Head;

    while (temp->next != NULL)
    {
      if (temp->next->val != val)
      {temp = temp->next;}
      else
      {
            temp->next = temp->next->next;
      }
    }
    return Head->next;
}Time: 8 ms                      beat:97.16%
Memory: 7.7MB            beat:92.71%



页: [1]
查看完整版本: LeetCode-203