写在前面
不自量力面试某公司算法工程师,惨不忍说之后决定从头学习算法。希望自己能够坚持 。
链表(入门)一共两道题。
题目来源
很随意地从链表开始刷题。
入门
题466:计算链表中有多少个节点.
样例:给出 1->3->5, 返回 3.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: the first node of linked list.
@return: An integer
"""
def countNodes(self, head):
# write your code here
# 一个一个数啊
count=0
while head:
count=count+1
head=head.next
return count
题452. 删除链表中的元素
删除链表中等于给定值val的所有节点。
样例:给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
def removeElements(self, head, val):
# write your code here
# 一个一个找,找到之后使它地前一个结点的next指向它地后一个结点
# 使用头结点处理边界问题
if head is None:
return None
new=ListNode(0)
new.next=head
head=new
pre=head
while pre.next is not None:
if pre.next.val==val:
pre.next=pre.next.next
else:
pre=pre.next
return new.next
写在后面
入门题主要为了了解链表的基本特征,下一步背书,比如数据结构。作者真的好菜的。