题解:
- 迭代法
- 递归法(操作链表的题目用递归,往往实现起来很简单,但是自己难想出来)
两种方法(或者其他方法),跟着模拟一遍就理解了。
代码:
/**
* 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) {
// 输入: 1->2->6->3->4->5->6, val = 6
// 输出: 1->2->3->4->5
/* 方法1:迭代 */
while(head != NULL && head->val == val)
{
head = head->next;
}
if(head != NULL)
{
ListNode* prev = head;
ListNode* current = head;
while(current != NULL)
{
if(current->val == val)
{
prev->next = prev->next->next;
}
else
{
prev = current;
}
current = current->next;
}
}
return head;
/* 方法2:递归
if(head == NULL)
{
return head;
}
head->next = removeElements(head->next,val);
if(head->val == val)
{
return head->next;
}
else
{
return head;
}*/
}
};