452. Remove Linked List Elements

452. Remove Linked List Elements

Description:

Remove all elements from a linked list of integers that have value val.

Example
Example 1:

Input: head = 1->2->3->3->4->5->3->null, val = 3
Output: 1->2->4->5->null
Example 2:

Input: head = 1->1->null, val = 1
Output: null

Main Idea:

Basic linked list problem.

Code:

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: a ListNode
     * @param val: An integer
     * @return: a ListNode
     */
    ListNode * removeElements(ListNode * head, int val) {
        // write your code here
        if(head == nullptr)
		return head;
		
    	ListNode* ptr = head, * pre = nullptr, *next = nullptr;
    	while(ptr){
    	    if(ptr->val == val){
    	        // if there is no previous node
    	        if(pre == nullptr){
    	            ptr = head = head->next;
    	            continue;
    	        }
    	        // if there exists previous node
    	        else {
    	            next = ptr->next;
    	            pre->next = next;
    	            ptr = next;
    	            continue;
    	        }
    	    }
    	    pre = ptr;
    	    ptr = ptr->next;
    	}
    	return head;
    }
};


发布了28 篇原创文章 · 获赞 1 · 访问量 423

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/104079249