zoukankan      html  css  js  c++  java
  • 《极客时间-算法面试》-数组和链表

    本文是学习《极客时间-面试》数组和链表中的内容。 

    目录

      1、翻转链表

      2、翻转链表对

      3、环链表

    题目一:翻转链表

    博客:翻转链表

    # -*- coding:utf-8 -*-
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        # 返回ListNode
        def ReverseList(self, pHead):
            # write code here
            '''
            cur,prev = pHead,None
            while cur:
                cur.next,prev,cur = prev,cur,cur.next
            return prev
            '''
            cur,prev,temp = pHead,None,None
            while cur:
                temp = cur.next
                cur.next = prev
                prev = cur
                cur = temp
            return prev

    题目二:翻转链表对

     

    1-2-3-4-5----------->>>>>2-1-4-3-5

    思路:需要定义三个指针,进行交换。

      定义前指针,指向两两节点。遍历时候单双节点个数,用后面的两个节点分别查看是否空节点,若空直接返回,之后进行两两交换节点。

    代码:代码采用了直接交换节点的方式,由于是python,否则要进行中间节点缓存。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def swapPairs(self, head: ListNode) -> ListNode:
            pre,pre.next = self,head                            #pre前指针
            while pre.next and pre.next.next:
                cur = pre.next                                  #当前指针
                xia = cur.next                                  #下一个指针
                pre.next,xia.next,cur.next = xia,cur,xia.next   #三个指针进行交换
                pre = cur                                       #将前指针指向已经调好顺序的后面节点
            return self.next                                    #返回self.next

     题目三:环链表,给定一个链表,判断是否有环

    思路:采用快慢指针,是否相遇。

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def hasCycle(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
            slow = fast = head                      #采用快慢指针,同时从头结点遍历
            while slow and fast and fast.next:      #开始遍历
                slow = slow.next                    #慢指针每次遍历一个节点
                fast = fast.next.next               #快指针每次遍历两个节点
                if slow is fast:                    #如果快慢指针相遇,那么该链表具有环
                    return True
            return False

     数组和链表

    想改变数组中的内容,采用插入和删除操作。插入O(n)时间复杂度

    插入节点操作

    删除节点操作

    数组在查询时候较快,但是插入删除较慢,链表相反,插入和删除较慢,但是查询需要一定的时间。

  • 相关阅读:
    2. Add Two Numbers
    1. Two Sum
    leetcode 213. 打家劫舍 II JAVA
    leetcode 48. 旋转图像 java
    leetcode 45. 跳跃游戏 II JAVA
    leetcode 42. 接雨水 JAVA
    40. 组合总和 II leetcode JAVA
    24. 两两交换链表中的节点 leetcode
    1002. 查找常用字符 leecode
    leetcode 23. 合并K个排序链表 JAVA
  • 原文地址:https://www.cnblogs.com/missidiot/p/10938465.html
Copyright © 2011-2022 走看看