LeetCode-203 移除链表元素

版权声明:本文为博主原创文章,但是欢迎转载! https://blog.csdn.net/yancola/article/details/87887345
 /*移除链表中的元素(带虚拟头节点版本)*/
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummyHead = new ListNode(-1);
		dummyHead->next = head;
		ListNode *preNode = dummyHead;
		while(preNode->next != nullptr)
		{
			if(preNode->next->val == val)
			{
				preNode->next = preNode->next->next;
			}
			else
			{
				preNode = preNode->next;
			}
		}
		
		return dummyHead->next;
    }
};
 /*移除链表中的元素(不带虚拟头节点版本)*/
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
		while(head != nullptr && head->val == val)
		{
			head = head->next;
		}
		if(head == nullptr)
		{
			return head;
		}
		ListNode preNode = head;
		while(preNode->next != nullptr)
		{
			if(preNode->next->val == val)
			{
				preNode->next = preNode->next->next;
			}
			else{
				preNode = preNode->next;
			}
		}
		return head;
    }
};
/*递归版本*/
ListNode *removeElements(ListNode *head, int val)
{
    if (head != nullptr)
        return head;
    head->next = removeElements(head->next, val);
    return head->val == val ? head->next : head;
}

猜你喜欢

转载自blog.csdn.net/yancola/article/details/87887345