链表总结V

反转链表Ⅱ
翻转链表
Leetcode21——合并两个有序的链表
【将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。】
题解

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """

        chushihua = ListNode(-1)
        temp = chushihua

        while list1 and list2:
            if list1.val <= list2.val:
                temp.next = list1
                list1 = list1.next
            else:
                temp.next = list2
                list2 = list2.next
            temp = temp.next
        
        temp.next = list1 if list1 else list2
        return chushihua.next

Leetcode203——移除链表元素
【给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。】
题解
都知道是要head.next = head.next.next, 但是head.next和head.next.next有可能不存在,因此需要初始化一个别的变量。
chushihua = ListNode(-1)
chushihua.next = head
new = chushihua

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        chushihua = ListNode(-1)
        chushihua.next = head
        cur = chushihua

        while cur.next:
            if cur.next.val == val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return chushihua.next

Leetcode206——反转链表
【给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。】
题解

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head: return head
        left, right = head,head.next
        head.next = None
        while right:
           temp = right.next
           right.next = left
           left,right = right,temp
        return left

Leetcode141——环形链表
【给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。如果链表中存在环 ,则返回 true 。 否则,返回 false 。】

题解

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """

        cur = head
        res = set()

        while cur:
            node = cur
            if node not in res:
                cur = cur.next
                res.add(node)
            else:
                return True
        return False

Leetcode-160相交链表
【给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。】
题解

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        p,q = headA, headB

        while not p == q:
            p= p.next if p else headB
            q = q.next if q else headA
        return p

Leetcode-83 删除有序链表中重复的元素
【给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。】
题解

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head : return

        cur = head

        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

Leetcode-19 删除链表倒数第N个节点
【给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。】
题解

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        chushihua = ListNode(-1)
        chushihua.next = head
        left, right = chushihua, chushihua
        while n:
            right = right.next
            n -= 1
        
        while right.next:
            left = left.next
            right = right.next
        left.next = left.next.next
        return chushihua.next

Leetcode-142 环形链表2
【给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。】
题解

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head: return
        temp = set()
        while head:
            if head in temp:
                return head
            else:
                temp.add(head)
            head = head.next
        return
            

剑指 Offer 22. 链表中倒数第k个节点
【输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。】

class Solution(object):
    def getKthFromEnd(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """

        left, right = head, head

        while k:
            if not right:return
            right = right.next
            k -= 1
        
        while right:
            right = right.next
            left = left.next
        
        return left

Leetcode-234 回文链表
【给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。】

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """

        temp = []
        while head:
            temp.append(head.val)
            head = head.next
        
        return temp == temp[::-1]

leetcode-92 反转链表2
【给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。】

class Solution(object):
    def reverseBetween(self, head, left, right):
        """
        :type head: ListNode
        :type left: int
        :type right: int
        :rtype: ListNode
        """

        dummy_node = ListNode(-1)
        dummy_node.next = head
        pre = dummy_node
        for _ in range(left - 1):
            pre = pre.next

        cur = pre.next
        for _ in range(right - left):
            next = cur.next
            cur.next = next.next
            next.next = pre.next
            pre.next = next
        return dummy_node.next

leetcode-25 翻转链表
【给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。】

class Solution:
    def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
        #找到每次翻转的尾部
        tail = head 
        #遍历k次到尾部
        for i in range(0,k): 
            #如果不足k到了链表尾,直接返回,不翻转
            if tail == None: 
                return head
            tail = tail.next
        #翻转时需要的前序和当前节点
        pre = None 
        cur = head
        #在到达当前段尾节点前
        while cur != tail: 
            #翻转
            temp = cur.next 
            cur.next = pre
            pre = cur
            cur = temp
        #当前尾指向下一段要翻转的链表
        head.next = self.reverseKGroup(tail, k) 
        return pre

leetcode-2 链表相加
【给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。】

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        stack1, stack2 = deque([]), deque([])
        while l1:
            stack1.append(l1.val)
            l1 = l1.next
        while l2:
            stack2.append(l2.val)
            l2 = l2.next

        carry, p = 0, None
        while stack1 or stack2 or carry:
            num1 = stack1.pop() if stack1 else 0
            num2 = stack2.pop() if stack2 else 0
            ans = num1 + num2 + carry
            carry = ans // 10
            ans %= 10
            p = ListNode(ans, p)
        return p

Leetcode-148 排序链表
【给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。】

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        temp = []
        while head:
            temp.append(head.val)
            head = head.next

        temp.sort()

        t = ListNode(-1)
        chushihua = t

        for x in temp:
            chushihua.next = ListNode(x)
            chushihua=chushihua.next
        return t.next

Leetcode-328 奇偶链表
【给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。】

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        
        evenHead = head.next
        odd, even = head, evenHead
        while even and even.next:
            odd.next = even.next
            odd = odd.next
            even.next = odd.next
            even = even.next
        odd.next = evenHead
        return head

Leetcode-82 删除排序链表中的重复元素 II
【给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。】

class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        chushihua = ListNode(-1)
        chushihua.next = head
        cur = chushihua
        
        while cur.next and cur.next.next:
           
            
            if cur.next.val == cur.next.next.val:
                x = cur.next.val
                while cur.next and cur.next.val==x:
                    cur.next = cur.next.next
            else:
                cur = cur.next
        return chushihua.next

Leetcode-23 合并k个升序链表

【给你一个链表数组,每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中,返回合并后的链表。】

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        import heapq
        dummy = ListNode(0)
        p = dummy
        head = []
        for i in range(len(lists)):
            if lists[i] :
                heapq.heappush(head, (lists[i].val, i))
                lists[i] = lists[i].next
        while head:
            val, idx = heapq.heappop(head)
            p.next = ListNode(val)
            p = p.next
            if lists[idx]:
                heapq.heappush(head, (lists[idx].val, idx))
                lists[idx] = lists[idx].next
        return dummy.next

剑指 Offer II 078. 合并排序链表
【给定一个链表数组,每个链表都已经按升序排列。请将所有链表合并到一个升序链表中,返回合并后的链表。 】

class Solution:
    def mergeKLists(self , lists: List[ListNode]) -> ListNode:
        # write code here
        
        if not lists:return None
        n = len(lists)
        return self.merge_sort(lists,0,n-1)
    
    def merge_sort(self,lists,l,r):
        if l==r:return lists[l]
        mid = (l+r)//2
        L = self.merge_sort(lists,l,mid)
        R = self.merge_sort(lists,mid+1,r)
        return self.merge(L,R)
    
    def merge(self,a,b):
        dummy = ListNode(-1)
        x = dummy
        
        while a and b:
            if a.val < b.val:
                x.next = a
                a = a.next
            else:
                x.next = b
                b = b.next
            x = x.next
        if a:
            x.next = a
        if b:
            x.next = b
        return dummy.next
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值