iT邦幫忙

2024 iThome 鐵人賽

DAY 3
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 3

Day03__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

203. Remove Linked List Elements

tags: Easy、Linked-List

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.

解法:

用簡單的移除list node的方式去解,要記得先處理頭指針

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    while (head != NULL && head->val == val) {
        struct ListNode *temp = head;
        head = head->next;
        free(temp);
    }    
    struct ListNode *current = head;

    while(current != NULL && current->next != NULL) {
        if (current->next->val == val) {
            struct ListNode *temp = current->next;
            current->next = current->next->next;
            free(temp);
        }
        
        else {
            current = current->next;
        }
    }
    return head; 
}

上一篇
Day02__C語言刷LeetCode
下一篇
Day04__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言