#707 Design Linked List
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes:valandnext.valis the value of the current node, andnextis a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attributeprevto indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.Implement the
MyLinkedListclass:
MyLinkedList()Initializes theMyLinkedListobject.int get(int index)Get the value of theindexthnode in the linked list. If the index is invalid, return-1.void addAtHead(int val)Add a node of valuevalbefore the first element of the linked list. After the insertion, the new node will be the first node of the linked list.void addAtTail(int val)Append a node of valuevalas the last element of the linked list.void addAtIndex(int index, int val)Add a node of valuevalbefore theindexthnode in the linked list. Ifindexequals the length of the linked list, the node will be appended to the end of the linked list. Ifindexis greater than the length, the node will not be inserted.void deleteAtIndex(int index)Delete theindexthnode in the linked list, if the index is valid.
解题思路:
1.先定义node,val和next
2.初始construction先定义size和第一个node,head
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
self.size = 0
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
if index < 0 or index >= self.size:
return -1
current = self.head
for _ in range(0, index):
current = current.next
return current.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be
the first node of the linked list.
"""
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked
list, the node will be appended to the end of linked list. If index is greater than the length, the node will not
be inserted.
"""
if index > self.size:
return
current = self.head
new_node = ListNode(val)
if index <= 0:
new_node.next = current
self.head = new_node
else:
for _ in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.size += 1
def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
if index < 0 or index >= self.size:
return
current = self.head
if index == 0:
self.head = self.head.next
else:
for _ in range(0, index - 1):
current = current.next
current.next = current.next.next
self.size -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
#141 Linked List Cycle
Given
head, the head of a linked list, determine if the linked list has a cycle in it.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the
nextpointer. Internally,posis used to denote the index of the node that tail'snextpointer is connected to. Note thatposis not passed as a parameter.Return
trueif there is a cycle in the linked list. Otherwise, returnfalse.
解题思路:
方法1.见过的点存到visited里,每往前走就检查是否visited过。见过就说明进入了循环,走到最后尽头是self.next是None的话就说明无循环。
方法2.龟兔赛跑,快指针与慢指针再次相遇说明有循环,快指针或快指针的下一个是None的话,说明无循环。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
visited = set()
while head is not None:
if head in visited:
return True
visited.add(head)
head = head.next
return False
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = slow = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False
设计单链表实现与环检测
本文介绍了如何使用Python实现单链表数据结构,包括初始化、节点操作(获取、头部添加、尾部添加、指定位置插入和删除)以及检测链表中是否存在循环。同时,提供了两种方法来判断链表是否有环:一种是利用visited集合,另一种是使用快慢指针。

被折叠的 条评论
为什么被折叠?



