Remove Linked List Elements(C++移除链表元素)

解题思路:

(1)使用两个指针,一个前指针,一个当前指针

(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 *pre = NULL,*curr = head;
		while(curr) {
			if (curr->val==val) { //删除元素为头结点 
				if (pre==NULL) head = head -> next; 
				else pre->next = curr->next;
				curr = curr->next;
			} else {
				pre = curr;
				curr = curr->next;
			}
		} 
		return head;
    }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105626484