标签:
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.
每次遇到链表操作,树操作的时候我的大脑就会messed up. 各种考虑不周全,各种edge case 失败。
思路分两步,第一步删除头,即比如要删除6,而链表是6->6->3->2。先把以目标6开头的链表变成不已目标开头的链表。
第二步就便利链表,如果发现next 是目标,就把当前的next 变为next->next。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* p = NULL; while (head != NULL && head->val == val) { head = head->next; } if (head == NULL) return NULL; p = head; while (p != NULL) { if (p->next != NULL && p->next->val == val) { p->next = p->next->next; } else { p = p->next; } } return head; }
[LeetCode] Remove Linked List Elements
标签:
原文地址:http://www.cnblogs.com/agentgamer/p/4901754.html