刪除鏈表中等於給定值 val 的所有節點。 示例: 輸入: 1->2->6->3->4->5->6, val = 6 輸出: 1->2->3->4->5 /** * Definition for singly-linked list. * struct ListNode { * int val; * ...
刪除鏈表中等於給定值 val 的所有節點。
示例:
輸入: 1->2->6->3->4->5->6, val = 6 輸出: 1->2->3->4->5
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* s = (struct ListNode* )malloc(sizeof(struct ListNode)); s->next = head; struct ListNode* pre = s; struct ListNode* cur = head; while (cur) { if (cur->val == val) { pre->next = cur->next; } else { pre = cur; } cur = cur->next; } return s->next; }