题目描述
Remove all elements from a linked list of integers that have value val.
题目大意:从链表中移除所有指定的元素
样例
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
python解法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head:
return None
p = r = ListNode(0)
p.next = head
q = head
while q:
if q.val == val:
p.next = q.next
else:
p = p.next
q = q.next
return r.next
Runtime: 68 ms, faster than 96.13% of Python3 online submissions for Remove Linked List Elements.
Memory Usage: 16.9 MB, less than 5.55% of Python3 online submissions for Remove Linked List Elements.
题后反思:
- 要注意从哪里开始循环,并且要有一个变量指向头结点
C语言解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *p = (struct ListNode*)malloc(sizeof(struct ListNode));
p -> next = head;
struct ListNode *q = head, *r = p;
while(q)
{
if (q -> val == val)
{
p -> next = q -> next;
}
else
{
p = p -> next;
}
q = q -> next;
}
return r -> next;
}
Runtime: 12 ms, faster than 77.10% of C online submissions for Remove Linked List Elements.
Memory Usage: 9.2 MB, less than 88.89% of C online submissions for Remove Linked List Elements.
题后反思:无
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步