题目
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
思路
链表节点的删除操作。
代码
/*---------------------------------------
* 日期:2015-05-01
* 作者:SJF0115
* 题目: 203.Remove Linked List Elements
* 网址:https://leetcode.com/problems/remove-linked-list-elements/
* 结果:AC
* 来源:LeetCode
* 博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr){}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head == nullptr){
return nullptr;
}//if
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = head;
ListNode* tmp;
while(cur){
if(cur->val == val){
tmp = cur;
pre->next = cur->next;
delete tmp;
cur = pre->next;
}//if
else{
pre = cur;
cur = cur->next;
}//else
}//while
return dummy->next;
}
};
int main() {
Solution solution;
ListNode* head = new ListNode(1);
ListNode* node1 = new ListNode(5);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(1);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(1);
head->next = node1;
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
head = solution.removeElements(head,6);
while(head){
cout<<head->val<<endl;
head = head->next;
}//while
}
运行时间
[LeetCode]203.Remove Linked List Elements
原文地址:http://blog.csdn.net/sunnyyoona/article/details/45437427