203. Remove Linked List Elements
来源:互联网 发布:java web九九乘法表 编辑:程序博客网 时间:2024/05/16 17:38
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.
添加dummy头结点,简化代码书写
/** * 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 NULL; ListNode *dummy = new ListNode(INT_MAX); dummy->next = head; ListNode *prev = dummy; ListNode *cur = head; while(cur) { if(cur->val != val) { cur = cur->next; prev = prev->next; } else { prev->next = cur->next; delete cur; cur = prev->next; } } return dummy->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) { if(head == NULL) return NULL; ListNode *res = head; ListNode *p = head; //处理末尾相等的情况 while(p && p->val == val) { ListNode *tmp = p; p = p-> next; delete tmp; } res = p; //处理中间相等的情况 while(p) { if(p -> next && p->next->val == val) { ListNode *tmp = p->next; p->next = p->next->next; delete tmp; continue; } p=p->next; } return res; }};
0 0
- 203. Remove Linked List Elements(Linked List)
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- 203. Remove Linked List Elements
- TN2277 Networking and Multitasking
- Volley框架的介绍使用
- [HTML]table选中行效果
- UVC 摄像头厂商列表
- sql server线程等待信息
- 203. Remove Linked List Elements
- c++中cstring向char c[1024]转换
- 【MongoDB】Java驱动下,反射实现DAO的写操作
- 深入A*算法
- Linux下安装jdk与tomcat
- 最近公共祖先LCA【模板】
- fsck(file system check)
- 单应矩阵计算 findHomography和getPerspectiveTransform区别
- 版本更新