链表leetcode

 23. 合并K个升序链表(困难 重要 待做)

206. 反转链表

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = None
        cur = head
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        return pre

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

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        h = ListNode(None)
        h.next = head
        pre = h
        while pre.next != None and pre.next.next != None:
            node1 = pre.next
            node2 = node1.next
            lat = node2.next

            pre.next = node2            
            node2.next = node1
            node1.next = lat
            
            pre = node1

        return h.next

25. K 个一组翻转链表 (困难 重要)

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        p1 = head
        length = 0
        while p1:
            length+=1
            p1=p1.next
        pre = None
        cur = head
        for i in range(length//k):
            start = pre #start
            end = cur
            for j in range(k):
                temp = cur.next
                cur.next = pre
                pre = cur
                cur = temp
            if start: #第一组除外都执行这一条
                start.next = pre
            else: #只在第一组的时候执行,为了让head等于第一组反转后的头
                head = pre
            end.next = cur #连接反转后的尾和未反转的头
            pre = end #pre改成未反转头的上一个节点
        return head

92. 反转链表 II  (还要再看,主要是不知道头尾连接怎么弄)

class Solution(object):
    def reverseBetween(self, head, left, right):
        """
        :type head: ListNode
        :type left: int
        :type right: int
        :rtype: ListNode
        """
        if not head or not head.next or left==right:
            return head
        dummy = ListNode(0)
        dummy.next = head
        start = dummy
        for i in range(left-1):
            start = start.next       
        end = cur = start.next  
        pre = None
        for i in range(right-left+1):
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp         
        start.next = pre
        end.next = cur
        return dummy.next


2. 两数相加 (出息了出息了 自己写的!)

# 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 addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(None)
        h = head
        if not l1:
            return l2
        if not l2:
            return l1
        flag = 0
        while l1 or l2:
            tmp_sum = 0
            if l1:
                tmp_sum += l1.val 
                l1 = l1.next
            if l2:
                tmp_sum += l2.val
                l2 = l2.next
            tmp_sum += flag
            if tmp_sum >= 10:
                h.next = ListNode(tmp_sum % 10)
                flag = 1
            else:
                h.next = ListNode(tmp_sum)
                flag = 0
            h = h.next
        if flag == 1:
            h.next = ListNode(1)
        return head.next

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

# 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 removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        a = head
        b = head
        for i in range(n):
            if a.next:
                a = a.next
            else:
                return head.next
        while a.next and b.next:
            a=a.next
            b=b.next
        b.next = b.next.next
        return head

21. 合并两个有序链表

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        node = ListNode(None)
        new = node
        while l1 and l2:
            if l1.val > l2.val:
                new.next = l2
                l2 = l2.next
            else:
                new.next = l1
                l1 = l1.next
            new = new.next
        if l1:
            new.next = l1
        if l2:
            new.next = l2
        return node.next

61. 旋转链表 (需要再看)

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        num = 0  # num是链表的节点数
        t = head
        while t: 
            t = t.next
            num += 1
        if num == 0 or num == 1: 
            return head
        k = k % num # k有可能大于num
        slow = head
        fast = head
        for i in range(k):
            fast = fast.next
        while fast.next:  #找到倒数第k个节点
            fast = fast.next
            slow = slow.next
        fast.next = head  #连接原链表的尾部和头部 尾部 -> 头部
        head = slow.next #head变成倒数第k个节点
        slow.next = None #slow就是旋转后的最后一个节点
        return head

83. 删除排序链表中的重复元素

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        p = head
        while p.next:
            if p.val == p.next.val:
                p.next = p.next.next
            else:
                p = p.next
        return head

 82. 删除排序链表中的重复元素 II

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        h = ListNode(-1)
        h.next = head
        pre = h
        cur = head
        while cur != None: 
            duplicate = False          
            while cur.next != None and cur.val == cur.next.val:
                cur = cur.next
                duplicate = True
            
            if duplicate == False:
                pre = cur
            else:
                pre.next = cur.next
            cur = cur.next

        return h.next

 86. 分隔链表

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        left_head = left = ListNode(0)   
        right_head = right = ListNode(0)
        while head:
            val = head.val
            if val < x:
                left.next = head
                left = left.next
            else:
                right.next = head
                right = right.next
            head = head.next
        right.next = None
        left.next = right_head.next 
        return left_head.next

 109. 有序链表转换二叉搜索树 (这个还需要手写递归过程 to 理解)

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        slow, fast = head, head
        pre = head
        while fast and fast.next:        
            pre = slow
            slow = slow.next
            fast = fast.next.next
            # print slow.val, fast.val, pre.val
        pre.next = None
        part1 = head #part1是有序数组的前半部分,也是BST的左子树
        part2 = slow.next #part2是有序数组的后半部分,也是BST的右子树
        
        root = TreeNode(slow.val)
        root.left = self.sortedListToBST(part1)
        root.right = self.sortedListToBST(part2)
        return root

138. 复制带随机指针的链表  (待做)

160. 相交链表

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        pA = headA
        pB = headB
        while pA != pB:
            if pA:
                pA = pA.next
            else:
                pA = headB
            if pB:
                pB = pB.next
            else:
                pB = headA
        return pA

234. 回文链表

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head:
            return True
        slow = head
        fast = head
        # 快指针指向下两个,这样遍历之后,slow只走到中间节点
        while fast:
            slow = slow.next
            if fast.next:
                fast = fast.next.next
            else:
                fast = fast.next
         
        # 将中间节点之后的链表反转
        p, rev = slow, None
        while p:
            rev, rev.next, p = p, rev, p.next
        
        # 重新以head开始比较反转后的链表
        while rev:
            if rev.val != head.val:
                return False
            rev = rev.next
            head = head.next
        return True

141. 环形链表

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = head
        fast = head
        if head == None:
            return False
        while slow.next and fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

142. 环形链表 II

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            # 如果相遇
            if slow == fast:
                p = head
                q = slow
                while p!=q:
                    p = p.next
                    q = q.next
                #你也可以return q
                return p

        return None

143. 重排链表  (要再看,会看不会写)

先找到链表的中点:快慢指针,考虑节点个数奇偶情况
再翻转后半段链表
最后两链表依次插入

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        # looking for the midpoint
        fast = slow = a = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next    
        b = slow.next if fast else slow
        
        # reverse
        pre = None
        cur = b
        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
            
        # cross
        b = pre
        while a:
            a.next, b = b, a.next
            a = a.next
        return head

146. LRU 缓存机制

 

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.cache = collections.OrderedDict()

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key not in self.cache:
            return -1
        value = self.cache.pop(key)
        self.cache[key] = value
        return value
            

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if key in self.cache:
            self.cache.pop(key)
            self.cache[key] = value
        else:
            if key in self.cache:
                self.cache[key] = value
            else:
                if len(self.cache) == self.capacity:
                    self.cache.popitem(last=False)
                    self.cache[key] = value
                else:
                    self.cache[key] = value

147. 对链表进行插入排序 (要再看)

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # 找个排头
        dummy = ListNode(-1)
        pre = dummy
        # 依次拿head节点
        cur = head
        while cur:
            # 把下一次节点保持下来
            tmp = cur.next
            # 找到插入的位置
            while pre.next and pre.next.val < cur.val:
                pre = pre.next
            # 进行插入操作
            cur.next = pre.next
            pre.next = cur
            pre = dummy
            cur = tmp
        return dummy.next

148. 排序链表 (不会)

 先折中归并排序,再合并两个有序链表.

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not (head and head.next):
            return head
        p1 = head
        p2 = head.next
        while p2 and p2.next:
            p1 = p1.next
            p2 = p2.next.next
        head2 = p1.next
        p1.next = None
        list1=self.sortList(head)
        list2=self.sortList(head2)
        myhead=ListNode(0)
        node=myhead
        while list1 and list2:
            if list1.val > list2.val:
                list1,list2 = list2,list1
            node.next = list1
            node = node.next
            list1 = list1.next
        if list1:
            node.next = list1
        else: 
            node.next = list2
        return myhead.next

203. 移除链表元素

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """ 
        if head == None:
            return head
        dummy_head = ListNode(next=head)
        res = dummy_head
        while res.next:
            if res.next.val == val:
                res.next = res.next.next
            else:
                res = res.next
        return dummy_head.next

237. 删除链表中的节点

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

328. 奇偶链表 (再看)

主要思路是逐个遍历链表中的元素,需要有四个指针分别指向奇数头,奇数尾,偶数头,偶数尾
当遍历到奇数结点时,奇数尾的next赋值为当前node,奇数尾指针指向当前node,偶数同理。
最后将奇数尾与偶数头相连,偶数尾指向None
返回奇数头即可。

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if (head == None) or (head.next == None):
            return head
        # 头标记
        oddHead = head
        evenHead = head.next
        # 尾标记
        oddEnd = oddHead
        evenEnd = evenHead
        # 循环迭代标记
        node = evenHead.next # 当前循环结点
        isOdd = True # 是否为奇数标记

        while(node!= None):
            #print(node.val)
            if isOdd:# 当前是奇数结点
                isOdd = False # 标记反转
                oddEnd.next = node # 奇数尾的next值指向当前结点
                oddEnd = node # 奇数尾指针向后移动
            else:
                isOdd = True
                evenEnd.next = node
                evenEnd = node
            node = node.next # 迭代下一个结点
        # 拼接奇偶链表
        oddEnd.next = evenHead # 奇数尾指向偶数头
        evenEnd.next = None # 偶数尾指向None
        return oddHead

 355. 设计推特 (待做)

369. 给单链表加一 (不是很理解list和原链表什么关系)

class Solution(object):
    def plusOne(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        lst = []
        ans = node = ListNode(0)
        node.next = head
        while node:
            lst.append(node) #lst存储链表
            node = node.next
        while lst:
            if lst[-1].val < 9:
                lst[-1].val += 1
                break
            else:
                lst[-1].val = 0
                lst.pop()

        if ans.val == 0: #如果最高位没有进位
            return ans.next
        else:
            return ans

379. 电话目录管理系统 (待做)

707. 设计链表 (待做)

猜你喜欢

转载自blog.csdn.net/weixin_39915444/article/details/121460705