题目:环形链表
链接:https://leetcode-cn.com/problems/linked-list-cycle/
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
例1:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
例2:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
思路一:
最简单的方法,就是遍历所有的节点,判断每个节点是否有超过一次询问的
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
listnode = set()
while head:
if head in listnode:
return True
listnode.add(head)
head = head.next
return False
思路二:
利用快慢指针,如果有环的话,快慢指针最后会相遇,如果没有,则快指针就会指向None
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
listnode_fast = head
listnode_slow = head
while listnode_fast and listnode_fast.next:
listnode_fast = listnode_fast.next.next
listnode_slow = listnode_slow.next
if listnode_fast == listnode_slow:
return True
return False
# if not head:
# return False
# listnode_fast = head.next
# listnode_slow = head
# while listnode_fast != listnode_slow:
# if not listnode_fast or not listnode_fast.next:
# return False
# listnode_fast = listnode_fast.next.next
# listnode_slow = listnode_slow.next
# return True
题目:回文链表
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnv1oc/
请判断一个链表是否为回文链表。
例1:
输入: 1->2
输出: false
例2:
输入: 1->2->2->1
输出: true
思路:
1、首先运用快慢指针确定链表的中点;
2、然后把后半部分进行翻转;
3、将前半部分和翻转后的后半部分进行比对
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
"""
:type head: ListNode
:rtype: bool
"""
# 翻转链表
def reverseList(head):
pre = None
cur = head
while cur:
tra = cur.next
cur.next = pre
pre = cur
cur = tra
return pre
# 确认链表中点
listnode_fast = head
listnode_slow = head
while listnode_fast and listnode_fast.next:
listnode_fast = listnode_fast.next.next
listnode_slow = listnode_slow.next
# 判断链表是否为奇数
if listnode_fast:
listnode_slow = listnode_slow.next
# 比对前后部分
listnode_fast = head
listnode_slow = reverseList(listnode_slow)
while listnode_slow:
if listnode_fast.val != listnode_slow.val:
return False
listnode_fast = listnode_fast.next
listnode_slow = listnode_slow.next
return True