标签:val remove for return value
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析:
将头结点赋值给一个临时节点,如果该节点的下一个节点不为空,递归遍历;
最后返回链表的头结点即可。
Code(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) {
while(head !=NULL && head->val == val) {
head = head->next;
}
if(head == NULL) return head;
ListNode* pre = NULL;
pre = head;
while(pre->next!=NULL){
if(pre->next->val == val){
pre->next = pre->next->next;
} else{
pre = pre->next;
}
}
return head;
}
};
Leetcode[203]-Remove Linked List Elements
标签:val remove for return value
原文地址:http://blog.csdn.net/dream_angel_z/article/details/46438785