【Leetcode】【Easy】Remove Linked List Elements
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
题目很简单,注意链表首结点有可能更改时,需新建preHead结点,或者使用二维指针的编程方法。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 if (head == NULL) 13 return head; 14 15 ListNode* prehead = new ListNode(0); 16 prehead->next = head; 17 ListNode* curNode = prehead; 18 19 while (curNode->next != NULL) { 20 if (curNode->next->val == val) 21 curNode->next = curNode->next->next; 22 else 23 curNode = curNode->next; 24 } 25 26 head = prehead->next; 27 delete prehead; 28 return head; 29 } 30 };