Remove Linked List Elements
来源:互联网 发布:linux 添加组 编辑:程序博客网 时间:2024/06/05 14:16
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
1、因为可能有表头是val的情况,设置辅助头结点 Head->next=head,
2、直接在链表中考虑,头结点移动,直到不是val时再进行判断
/** * 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 head; ListNode* Head=new ListNode(-1); Head->next=head; ListNode* cur=Head; while(cur->next!=NULL && cur!=NULL) { if(cur->next->val==val) { cur->next=cur->next->next; } else { cur=cur->next; } } return Head->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* cur=head; while(cur->val==val) { cur=cur->next; if(cur==NULL) return NULL; } head=cur; ListNode* temp=head; while(temp->next!=NULL) { if(temp->next->val==val) { temp->next=temp->next->next; } else { temp=temp->next; } } return head; }};
0 0
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- Remove Linked List Elements
- E A S Y 实现文件上传下载【更新版本】
- 纯CSS视差滚动
- UVA327Evaluating Simple C Expressions
- Android之MVP(二)之深入封装
- 【HDU 1175】连连看(DFS)
- Remove Linked List Elements
- 如何在ubuntu下安装vmware-tools
- Java进阶(三十五)java int与integer的区别
- 基于Oracle数据库的检索优化研究与分析
- Android收集应用崩溃信息
- Python——5函数
- hdu 5726 GCD(2016 Multi-University Training Contest 1线段树)
- CODEFORCES 450D Jzzhu and Cities <最短路径>
- 人民币即期汇率近六年首次跌破6.70 对国际消费影响几何