LeetCode:链表(3)

LeetCode:链表(3)

文章目录

  • LeetCode:链表(3)
    • 876. 链表的中间结点
    • 1290. 二进制链表转整数
    • 19. 删除链表的倒数第 N 个结点
    • 24. 两两交换链表中的节点

876. 链表的中间结点

LeetCode:链表(3)_第1张图片

class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        lst = []
        cur = head
        count = 0
        while cur:
            lst.append(cur.val)
            cur = cur.next
            count +=1
        for i in range(count//2):
            head = head.next
        return head

LeetCode:链表(3)_第2张图片

1290. 二进制链表转整数

LeetCode:链表(3)_第3张图片

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        cur = head
        str1 = ''
        while cur:
            str1 += str(cur.val)
            cur = cur.next
        return int(str1,2)
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        res = 0
        while head:  
            res = res * 2 + head.val # 相当于rec = rec<<1 | head.val
            head = head.next
        return res

19. 删除链表的倒数第 N 个结点

LeetCode:链表(3)_第4张图片
思路1:

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        count = 0
        cur = head
        while cur:
            count+=1
            cur = cur.next
        count -=n
        cur = head
        if count == 0:
            head = head.next
            return head
        for i in range(count-1):
            cur = cur.next

        if cur.next.next == None:
            cur.next = None
        else:
            cur.next = cur.next.next
        return head

思路1:优化

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        #优化思路1
        count,cur = 0,head
        while cur:
            count+=1
            cur = cur.next
        cur = head
        if count == n:
            head = head.next
            return head
        for i in range(count-1-n):
            cur = cur.next
        cur.next = cur.next.next
        return head

思路2:快慢指针
LeetCode:链表(3)_第5张图片

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        #思路2
        prev,cur = head,head
        for i in range(n):
            prev = prev.next
        if prev == None:
            head = head.next
            return head
        while prev.next:
            prev = prev.next
            cur = cur.next
        cur.next = cur.next.next
        return head

24. 两两交换链表中的节点

LeetCode:链表(3)_第6张图片
LeetCode:链表(3)_第7张图片

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummyHead = ListNode(0)
        dummyHead.next = head
        temp = dummyHead
        while temp.next and temp.next.next:
            node1 = temp.next
            node2 = temp.next.next
            temp.next = node2
            node1.next = node2.next
            node2.next = node1
            temp = node1
        return dummyHead.next

你可能感兴趣的:(LeetCode)