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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解法1:(1)如果链表最前面的若干个元素就是待删除元素,则删除之;(2)如果此时链表非空,则定义两个指针curr和next指向相邻两个节点,并不断往后遍历。如果next指向节点待删除节点,则删除之。直到next元素为尾节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { while(head != NULL && head->val == val) { ListNode* del = head; head = head->next; delete del; } if(head == NULL) return NULL; ListNode *curr = head, *next = head->next; while(next != NULL) { if(next->val == val) { ListNode* del = next; next = next->next; curr->next = next; delete del; } else { curr = next; next = next->next; } } return head; } };
注意next节点为待删除节点和非删除节点时处理的差异。
解法2:更方便的方法是在头节点前加入一个辅助节点,那么处理头节点就可以和处理普通节点一样了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* help = new ListNode(0); help->next = head; ListNode *curr = help, *next = head; while(next != NULL) { if(next->val == val) { ListNode* del = next; next = next->next; curr->next = next; delete del; } else { curr = next; next = next->next; } } return help->next; } };