Reverse every k nodes of a linked list

前端 未结 7 997
夕颜
夕颜 2020-12-15 01:42

I am preparing for a technical interview and I am stuck at writing this program to reverse every k nodes of a linked list.

For example

1->2->3         


        
相关标签:
7条回答
  • 2020-12-15 02:08

    I would do something like this:

    init curr (node pointer) to point to the beginning of the list.
    while end of list is not reached (by curr):
    - reverse(curr, k)
    - advance curr k times
    

    and reverse is a function that reverses the first k elements starting from curr.

    this might not be the most elegant or the most efficient implementation, but it works and is quite simple.

    to answer regarding the code you added:

    you returned prev, which is constantly being advanced. you should return the beginning of the list.

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