首页 > 其他分享 >day4-linked list-part02-7.6

day4-linked list-part02-7.6

时间:2024-07-09 15:26:09浏览次数:19  
标签:node head slow day4 part02 fast Next 7.6 next

task for today

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

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

3. 面试题 02.07. 链表相交

4. 142.环形链表II

-------------------------------------------------------------------

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

In this practice, pay attention to following several key points:

(1) dummy point is still recommended;

(2) the condition for while loop to execute the swap operation;

(3) node at odd position should be reserved as "temp=cur.next" and "temp1=cur.next.next.next" for avoiding being modified;

(4) the special circumstances of none head or single node

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # special cases
        if not head or not head.next:
            return head
        
        # create dummy node
        dummy_node = ListNode(next=head)
        cur = dummy_node
        
        # the condition for while loop
        while cur.next and cur.next.next:
            # reserve odd position node
            temp = cur.next
            temp1 = cur.next.next.next

            cur.next = cur.next.next
            cur.next.next = temp
            temp.next = temp1
            cur = cur.next.next

        return dummy_node.next

Here are the corresponding version for Go

func swapPairs(head *ListNode) *ListNode {
    // special circumstance
    if head == nil || head.Next == nil {
        return head
    }
    // dummmy node
    dummy_node := &ListNode{}
    dummy_node.Next = head

    cur := dummy_node

    // condition for while loop
    for cur.Next != nil && cur.Next.Next != nil {
        temp := cur.Next
        temp1 := cur.Next.Next.Next

        cur.Next = cur.Next.Next
        cur.Next.Next = temp
        temp.Next = temp1
        cur = cur.Next.Next
    }
    return dummy_node.Next
}

Use Rust to code linked list related practice is too disgusting, so I skip rust in linked list part ;-|

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

In this practice, it is more desirable to finish it just within once going-through. Therefore, double pointer mindset should be recalled. Following points should be paid attention to.

(1) dummy node is still needed;

(2) slow and fast both start from dummy node

(3) fast should firsly go (n+1) step, which is more convinent as the slow would stop at the node in front of the node penidng to be deleted.

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        # dummy node
        dummy_node = ListNode(next=head)
        slow = dummy_node
        fast = dummy_node

        # start to move fast for n+1 steps
        for i in range(n + 1):
            fast = fast.next

        # start to simultaneously move fast and slow
        while fast:
            slow = slow.next
            fast = fast.next
        
        # do the deleting
        slow.next = slow.next.next

        return dummy_node.next

Go version

func removeNthFromEnd(head *ListNode, n int) *ListNode {
    // dummy node
    dummy_node := &ListNode{}
    dummy_node.Next = head

    slow := dummy_node
    fast := dummy_node

    // move fast for n+1 steps
    for i := 0; i < n+1; i++ {
        fast = fast.Next
    }

    // move slow and fast simultaneously until fast point to None 
    for fast != nil {
        slow = slow.Next
        fast = fast.Next
    }

    // do the deleting
    slow.Next = slow.Next.Next

    return dummy_node.Next
}

3. 面试题 02.07. 链表相交

In this practice, the key point is to find the difference of the two linked list's length, here are the key steps:

(1) find each length

(2) calculate the difference

(3) move the longer pointer to align with the shorter pointer

(4) move together to find the intersection

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        # derive the length for two linked list
        lenA, lenB = 0, 0
        curA, curB = headA, headB
        while curA:
            curA = curA.next
            lenA += 1
        while curB:
            curB = curB.next
            lenB += 1

        # move the longer one first to align with the shorter one
        if lenA > lenB:
            diff = lenA - lenB
            curA = headA
            curB = headB
            for i in range(diff):
                curA = curA.next
        else:
            diff = lenB - lenA
            curA = headA
            curB = headB
            for i in range(diff):
                curB = curB.next
        
        # move together to find the intersection node
        while curA != curB:
            curA = curA.next
            curB = curB.next
        
        return curA

GO verion

func getIntersectionNode(headA, headB *ListNode) *ListNode {
    // find length
    lenA := 0
    lenB := 0
    curA := headA
    curB := headB
    for curA != nil {
        curA = curA.Next
        lenA += 1
    }
    for curB != nil {
        curB = curB.Next
        lenB += 1
    }

    if lenA > lenB {
        diff := lenA - lenB
        curA = headA
        curB = headB
        for i := 0; i < diff; i++ {
            curA = curA.Next
        }
    } else {
        diff := lenB - lenA
        curA = headA
        curB = headB
        for i := 0; i < diff; i++ {
            curB = curB.Next
        }
    }

    for curA != curB {
        curA = curA.Next
        curB = curB.Next
    }

    return curA
}

4. 142.环形链表II

In this practice, three key points need to be clear:

(1) decide whether there is a circle, use fast and slow pointer, if they meet, then there must be a circle;

(2) since they will meet within the circle, which will be position: let the line part is x, length between meetup point and entrance of the circle is y, "the other way around" length is z, which makes the circle circumvent is (y + z);

when they meet, the distance of fast should be twice as that of short one, which gives: (x + y) * 2 = x + y + (y + z) * n, where n represents the circles that fast pointer have finished before meeting slow pointer.

this equation gives results: x = z + (n - 1)*(y + z), this represent the line part equals to the z, as (n - 1)*(y + z) represents the circles which can be offset

(3) based on (2), set two pointers, respectively starting from head and meetup node, both with speed 1 node/setp, they will meet at the entrance node of the circle.

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head
        # move fast and slow
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

            # meet up
            if slow == fast:
                # move one to head
                slow = head
                # move at same speed
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                # meet node will be the entrance of circle       
                return slow
        # no circle return
        return None

Go version

func detectCycle(head *ListNode) *ListNode {
    slow := head
    fast := head

    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next

        if slow == fast {
            slow = head

            for slow != fast {
                slow = slow.Next
                fast = fast.Next
            }
            return slow
        }
    }
    return nil 
}

标签:node,head,slow,day4,part02,fast,Next,7.6,next
From: https://blog.csdn.net/bbrruunnoo/article/details/140224691

相关文章

  • MathType7.6.4.58中文永久破解版激活码许可证 附带安装包下载地址
    亲爱的学霸们和学术大拿们,你们是否有过为数学公式的排版烦恼的时刻?今天我要向你们介绍一个神奇的软件—MathType,它能够让你轻松地编辑、复制和粘贴复杂的数学公式,无论是在Word文档、PowerPoint演示文稿还是任何需要数学表达的地方!MathType最新mac官方版本下载如下:https://wm......
  • 大数据之路 读书笔记 Day4 数据同步
    回顾:Day3总结了无限客户端的日志采集大数据之路读书笔记Day3Day2总结了浏览器端的日志采集大数据之路读书笔记Day2数据同步阿里数据体系中的数据同步,主要指的是在不同的数据存储系统之间进行数据的传输与更新,以保证数据的一致性和实时性。这个过程通常涉及......
  • 第一周总结(2024.7.6)
     这周是上小学期的第一周,内容是数据结构,第一阶段是布置在pta上的程序,包括一个图的应用和一个排序算法,剩下的两个编程自选。图论的部分我选的是迪杰斯特拉算法的应用,排序选的是希尔排序,我通过这个小学期的第一阶段复习了数据结构的算法并应用更加熟练。 在过去的一周我安装了h......
  • 7.6 【最有毅力的一集】
    今天衬衫大赛\(T_B\),选择了打表,于是手搓了\(36\)个表,由@lty_ylzsx专门打了一个程序检测表的正确性,局长负责将表转化为代码交上去,于是机房瞎了两双眼睛废了一双手……最后我换成自己的号交了\(78\)发测出了错误的表竟是最后一个\(9\times9\)的,于是改了就过了。总而言之......
  • 2024.7.6
    java流式streamflitermapskipforeachcollect...sparkstream关闭方法publicclassSparkStreaming08_Close_1{publicstaticvoidmain(String[]args)throwsException{SparkConfconf=newSparkConf();conf.setMaster("local[*]&quo......
  • 24.7.1 - 24.7.6 总结
    这周学习内容:数据结构相关:莫队,不删除莫队本质探讨,将dsuontree也视做一种莫队,并使用哈夫曼树和分治两种方法学习了子树补的不删除莫队。树分块topcluster法的构造与运用,以及虚树简单回顾(这个我自己整的)半平面相关的简单问题,使用分块解决。Boruvka算法解决完全图最小生......
  • 算法入门(4) 7.6
    [NOIP2008普及组]ISBN号码题目描述每一本正式出版的图书都有一个ISBN号码与之对应,ISBN码包括$9$位数字、$1$位识别码和$3$位分隔符,其规定格式如x-xxx-xxxxx-x,其中符号-就是分隔符(键盘上的减号),最后一位是识别码,例如0-670-82162-4就是一个标准的ISBN码。ISBN码......
  • 7.6 第一周总结
    #include<iostream>usingnamespacestd;voidSelect(int**pos,intn,intnum);intmain(){intnum;//皇后数cin>>num;int**pos;//皇后摆放矩阵pos=newint*[num];for(inti=0;i<num;i++){pos[i]=new......
  • 2024.7.6 鲜花
    梅菲斯特——女王蜂fromK8Heラストチャンスに飢えたつま先が踊り出すまま駆けたこの夜空並のスタンスじゃ靡かない星は宝石の憧れ浮かぶ涙と汗は血の名残り目の中でしか泳げなきゃ芝居だけどステージが逃がさないいついつまでも憧れ焦がれているよI’veneverseen......
  • 7.6
    今天配置了finalshell远程连接linux并且学了文件类指令学习时间:两小时代码时间:半小时1)pwd显示当前工作目录2)、ls列出目录的内容ls:列出当前目录中的文件和子目录。ls-l:以长格式列出当前目录中的文件和子目录,包括文件权限、所有者、文件大小、修改日期等详细信息。ls......