|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
从链表中删除所有指定值的节点
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
- //节点定义
- struct ListNode
- {
- int val;
- ListNode *next;
- ListNode(int x) : val(x), next(NULL) {}
- };
复制代码
我的代码
- ListNode* removeElements(ListNode* head, int val) {
- if (head == NULL) return head;
- if (head->next == NULL)
- {
- if(head->val == val) return NULL;
- else return head;
- }
-
- ListNode* it = head;
- while(it->next)
- {
- if(it->next->val == val)
- {
- it->next = it->next->next;
- }
- it = it->next;
- }
- if(it->val == val) it = NULL; //it此时为最后一个节点,单独处理
- if(head->val == val) //单独处理表头
- {
- if(head->next == NULL) return NULL;
- else
- {
- head = head->next;
- }
- }
- return head;
- }
复制代码
比如输入链表1->1->1,删除1,就不对,不知道哪里错了,希望高手能指点一下 |
|