Problem Description:
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
题目大意:
去掉单向链表中所有值与给定值相等的结点。
Solutions:
保存之前的结点,然后扫描每个节点即可。注意头结点是否会被去掉的问题。
Code in C++:
/**
* 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) {
if(!head) return head;
ListNode * prev = head;
ListNode * cur = prev->next;
while(prev->next)
{
if(cur->val == val){
prev->next = cur->next;
cur=prev->next;
}else{
prev= cur;
cur = prev->next;
}
}
if(head->val == val) return head->next;
return head;
}
};
近期评论