标签:
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
思路:简单题。
//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 fakeHead = ListNode(0); //伪头部,化简代码 fakeHead.next = head; ListNode *p = &fakeHead; while(NULL != p->next) { if(p->next->val == val) //当前数字的下一个需要被删除 删掉后重新判断当前位置的下一个数 p->next = p->next->next; else //当前位置的下一个不需要删除,把当前位置后移 p = p->next; } return fakeHead.next; } };
【leetcode】Remove Linked List Elements(easy)
标签:
原文地址:http://www.cnblogs.com/dplearning/p/4481042.html