一. 题目描述
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.
二. 题目分析
题目大意是从单链表中移除所有值为val的元素。在循环遍历链表时使用cur记录当前元素。注意多种临界情况,如头结点为NULL的时候。
三. 示例代码
// C++版本
ListNode* removeElements(ListNode* head, int val) {
ListNode* cur = head;
while (true) {
if (head == NULL) return NULL;
if (cur->val != val) break;
cur = cur->next;
head = cur;
}
while (cur->next) {
if (cur->next->val == val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return head;
}
// Python版本
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
pre = ListNode(0)
pre.next = head
cur = pre
while cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return pre.next
四. 小结
以上代码可以AC,但在编写过程中并没有考虑delete节点的问题,这样是不对的,由于时间有限,只能下次再改进了。