leetcode(1)链表

编程入门 行业动态 更新时间:2024-10-23 04:40:50

leetcode(1)<a href=https://www.elefans.com/category/jswz/34/1769662.html style=链表"/>

leetcode(1)链表

# 1. 定义一个链表节点
class ListNode:def __init__(self, val=0, next_node=None):self.val = valself.next_node = next_node# 2. 定义一个 node头节点
class LinkedList:def __init__(self):self.head = None# 3.链表查找元素 get(index):
def get_node(self, index):count = 0cur = self.headwhile cur is not None and count < index - 1:count += 1cur = cur.next_nodeif cur is None:return -1return cur.val# 4.1 链表头部插入元素
def insert_head(self, val):node = ListNode(val)node.next_node = self.head.next_nodeself.head.next_node = node# 4.2 链表尾部插入元素
def insert_tail(self, val):node = ListNode(val)cur = self.head# 遍历链表 直到尾部while cur.next_node is not None:cur = cur.next_nodecur.next_node = node# 4.3 链表中第i个元素后插入元素
def insert_inside(self, index, val):count = 1cur = self.headif index <= 0:node = ListNode(val)node.next_node = self.head.next_nodeself.head.next_node = nodewhile cur is not None and count < index - 1:count += 1cur = cur.next_nodeif cur is None:return -1node = ListNode(val)node.next_node = cur.next_nodecur.next_node = node# 链表  删除第i个元素
def remove_inside(self, index):count = 0cur = self.headwhile cur.next_node and count < index - 1:count += 1cur = cur.next_nodeif cur is None:return -1del_node = cur.next_nodecur.next_node = del_node.next_node# 翻转 链表
class Solution1:def reverse_list(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:tmp = cur.next  # 暂存后继节点 这里存储的是第二个节点cur.next = pre  # 修改 next 引用指向,这里指向的是最后一个元素pre = cur  # pre   当前节点完成修改指向操作后,pre指向当前节点cur = tmp  # cur   当前节点完成修改指向操作后,cur指向下一个节点return pre# 删除链表指定元素
class Solution2:def remove_elements(self, head: ListNode, val: int) -> ListNode:# 先移除头元素while head is not None and head.val == val:head = head.nextif head is None:return# 再移除后续元素pre = headwhile pre.next:if pre.next.val == val:pre.next = pre.next.nextelse:pre = pre.nextreturn head#  奇偶链表
class Solution3:def oddEvenList(self, head: ListNode) -> ListNode:if not head:return headodd = headeven_head = even = head.nextwhile odd.next and even.next: # 这里面的条件存在 如果当链表是奇数个# 奇数的下下个是奇数 同理偶数也一样odd.next = odd.next.nexteven.next = even.next.next# 奇数链表和奇数链表拼接 偶数同理odd,even = odd.next,even.nextodd.next = even_headreturn head# 回文链表
class Solution4:def isPalindrome(self, head: ListNode) -> bool:vals = []current_node = headwhile current_node is not None:vals.append(current_node.val)current_node = current_node.nextreturn vals == vals[::-1]# 深拷贝随机链表
class Solution5:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':dummy = Node(-1000000)newCurr = dummycurr = headnode2node = {}while curr:n = Node(curr.val, curr.next, curr.random)node2node[curr] = nnewCurr.next = nnewCurr = newCurr.nextcurr = curr.nextcurr = dummy.nextwhile curr:if curr.random:curr.random = node2node[curr.random]curr = curr.nextreturn dummy.next
# 链表 插入排序
class Solution6:def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head:return headdummy = ListNode(float('-inf'))node1,node2 = dummy,headwhile node2:nt = node2.nextwhile node1.next and node1.next.val<=node2.val:node1 = node1.nextnode1.next,node2.next = node2,node1.nextnode1,node2 = dummy,ntreturn dummy.next# 合并两个有序链表
class Solution7:def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:if not l1: return l2  # 终止条件,直到两个链表都空if not l2: return l1if l1.val <= l2.val:  # 递归调用l1.next = self.mergeTwoLists(l1.next,l2)return l1else:l2.next = self.mergeTwoLists(l1,l2.next)return l2
# 归并排序 排序列表
class Solution8:def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:if not head or not head.next:return headdummy = ListNode(float('-inf'))def merge(left, right):node = dummywhile left and right:if left.val < right.val:node.next = leftnode = leftleft = left.nextelse:node.next = rightnode = rightright = right.nextnode.next = left if left else rightreturn dummy.nextdef merge_sort(head):fast = slow = headwhile fast.next and fast.next.next:fast = fast.next.nextslow = slow.nextslow.next,slow = None,slow.nextleft = merge_sort(head) if head.next else headright = merge_sort(slow) if slow.next else slowreturn merge(left, right)return merge_sort(head)# 环形链表 快慢指针
class Solution9:def hasCycle(self, head: Optional[ListNode]) -> bool:if head == None or head.next == None: return Falseslow = headfast = head.nextwhile fast != slow:if fast.next == None or fast.next.next == None: return Falseslow = slow.nextfast = fast.next.nextreturn True# 环形链表 2
class Solution10(object):def detectCycle(self, head):fast, slow = head, headwhile True:if not (fast and fast.next): returnfast, slow = fast.next.next, slow.nextif fast == slow: breakfast = headwhile fast != slow:fast, slow = fast.next, slow.nextreturn fast# 删除倒数第n个节点
class Solution11:def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:pre = ListNode(0, head)   # 伪头节点node = pre    # 当前节点,初始化为伪头节点idx = 0    # 节点编号,初始为0node_map = {}   # 哈希表存储节点编号和节点while node:    # 遍历链表,idx最终为节点总个数node_map[idx] = nodenode = node.nextidx += 1node_map[idx - n - 1].next = node_map[idx - n].next  # 根据节点编号获取删除节点的前一个节点和要删除的节点return pre.next    # 返回头节点

更多推荐

leetcode(1)链表

本文发布于:2023-12-07 13:56:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1671371.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:链表   leetcode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!