Runner technique to combine two equal Linked Lists

前端 未结 2 1572
夕颜
夕颜 2021-02-04 04:17

So, I am facing a doubt here.

I was reading the book Cracking the coding Interview. The following text is written over there.

Suppose you had a linked list

相关标签:
2条回答
  • 2021-02-04 04:28

    Start p2 at second position.

    a1(p1)-> a2 (p2) -> a3 -> a4 -> b1 -> b2 -> b3 -> b4  
    a1-> a2 (p1) -> a3 -> a4 (p2)-> b1 -> b2 -> b3 -> b4  
    a1-> a2  -> a3(p1) -> a4 -> b1 -> b2(p2) -> b3 -> b4  
    a1-> a2  -> a3 -> a4(p1) -> b1 -> b2 -> b3 -> b4(p2)  
    
    0 讨论(0)
  • 2021-02-04 04:46

    Let n = 2. We are starting with a list:

    a1 -> a2 -> b1 -> b2
    

    Let p1 be a "fast" pointer initially pointing to the successor of head.
    Let p2 be a "slow" pointer initially pointing to the head.

          p1
    a1 -> a2 -> b1 -> b2
    p2
    

    We move p1 by two and p2 by one until p1 reaches the end of the list (there is no next).

                      p1
    a1 -> a2 -> b1 -> b2
          p2
    

    Move p1 back to the head.

    p1                  
    a1 -> a2 -> b1 -> b2
          p2
    

    Advance p2.

    p1                  
    a1 -> a2 -> b1 -> b2
                p2
    

    "Weaving" starts.

    Take element pointed by p2 and move it after p1. Advance p1 after inserted element.

                p1                  
    a1 -> b1 -> a2 -> b2
                      p2
    

    Take element pointed by p2 and move it after p1. Advance p1 after inserted element.

                           p1      
    a1 -> b1 -> a2 -> b2  
                      p2
    

    p1 is null, terminate.

    0 讨论(0)
提交回复
热议问题