leetcode 203. 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
思路:声明两指针,类似快慢指针,快指针遇到val时跳过,直到值不是val这时修改慢指针的next为快指针,慢指针移到快指针这个位置。
/**
* 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* p = head;
ListNode* q = head;
while (p && q) {
if(p->val == val) {
if (p == head) {
head = p->next;
q = head;
} else {
while (p && p->val == val) p = p->next;
q->next = p;
}
}
q = p;
if (p) p = p->next;
}
return head;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: