How to reverse a singly-linked list in blocks of some given size in O(n) time in place?

前端 未结 4 802
梦如初夏
梦如初夏 2021-01-13 15:20

I recently encounter an algorithm problem:

Reverse a singly-linked list in blocks of k in place. An iterative approach is preferred.

4条回答
  •  醉梦人生
    2021-01-13 15:49

    The easiest way to reverse the single linked list is as follows.

    private void reverse(Node node)
    {
        Node current = Node;
        Node prev = null;
        Node next = null;
    
        if(node == null || node.next == null)
        {
            return node;
        }
    
        while(current != null)
        {
            next = current.next;
            //swap
            current.next = prev;
            prev = current;
            current = next;
        }
        node.next = current;
    }
    

提交回复
热议问题