Leetcode[142][206] python实现 链表
构造单链表
class Node(object):
"""节点"""
def __init__(self, elem):
self.elem = elem # 存入数据
self.next = None # 初始设置下一节点为空
# 下面创建单链表,并实现其应有的功能
class LinkList(object):
"""单链表"""
def __init__(self):
self.__head = None
def is_empty(self): # 判断链表是否为空
return self.__head == None
def length(self): # 求链表长度
# cur游标,用来移动遍历节点
cur = self.__head
# count记录数量
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self): # 遍历整个列表
cur = self.__head
while cur != None:
print(cur.elem, end=' ')
cur = cur.next
print("\n")
def add(self, item): # 头插法添加结点
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item): # 尾插法添加结点
node = Node(item)
# 由于特殊情况当链表为空时没有next,所以在前面要做个判断
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, pos, item): # 往指定结点(第pos个&序号为pos-1)后添加结点
if pos <= 0:
# 如果pos位置在0或者以前,那么都当做头插法来做
self.add(item)
elif pos >= self.length():
# 如果pos位置比原链表长,那么都当做尾插法来做
self.append(item)
else: # 常规情况
per = self.__head
count = 0
while count < pos - 1:
count += 1
per = per.next
# 当循环退出后,per指向pos-1位置
node = Node(item)
node.next = per.next
per.next = node
def remove(self, item): # 删除链表中特定值节点
cur = self.__head
per = None
while cur != None:
if cur.elem == item:
# 先判断该节点是否是头结点
if cur == self.__head:
self.__head = cur.next
else:
per.next = cur.next
break
else:
per = cur
cur = cur.next
def search(self, item): # 查找特定值节点是否存在
cur = self.__head
while cur:
if cur.elem == item:
return True
else:
cur = cur.next
return False
if __name__ == "__main__":
# 当.py文件单独运行时,此代码块会被运行
# 当.py以模块形式被导入,此代码块不运行
ll = LinkList()
print(ll.is_empty())
print(ll.length())
ll.append(3)
ll.add(999)
ll.insert(-3, 110)
ll.insert(99, 111)
print(ll.is_empty())
print(ll.length())
ll.travel()
ll.remove(111)
ll.travel()
print(ll.search(110))
Leetcode (142) 环形链表II
题目
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
分析
法1:
与昨天的集合有关系,遍历链表的同时将未加入set中的结点加入,直至第一次发现set中已有的结点,输出该结点。
要注意的是set中要放入ListNode而不是单独把node.val数值放入,因为本身链表的元素值可能有重复。
法2:
创建两个结点,快结点是慢节点的两倍速度,当两者在环中相遇时,可推出慢节点到第一个环结点的距离与头结点到第一个环结点的距离相同(帮助我复习了一下高中物理的相对速度的知识)。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle1(self, head): # 56ms
"""
:type head: ListNode
:rtype: ListNode
"""
a = set()
while head:
if head in a:
return head
else:
a.add(head)
head = head.next
return None
def detectCycle2(self, head): #56ms
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return None
slow = fast = head
while(slow and fast and fast.next):
slow = slow.next
fast = fast.next.next
if(slow == fast):
a = head
while slow != a:
a = a.next
slow = slow.next
return a
return None
学习心得
了解了set中不只可以单纯放数字,还可以放此前定义的Node。
温习了set的知识
Python中指针不用node->next(C++表示),而是node.next
Leetcode (204) 反转链表
题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
分析
设置三个指针,分别指向当前要操作的指针,及其前后。循环,需要注意的是指定指针的顺序不能乱,有些类似于构造单链表的insert函数。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return head
cur = head
pre = None
nt = cur.next
while nt:
cur.next = pre
pre = cur
cur = nt
nt = nt.next
cur.next = pre
head = cur
return head