Reversing a singly linked list iteratively

后端 未结 7 1247
情话喂你
情话喂你 2021-01-01 08:17

Has to be O(n) and in-place (space complexity of 1). The code below does work, but is there a simpler or better way?

public void invert() {
    if (this.getH         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 08:43

    public void invert() {  
      if (first == null) return;  
      Node prev = null;  
      for ( Node next = first.next; next != null; next = first.next) {  
        first.next = prev;  
        prev = first;  
        first = next;  
      }  
      first.next = prev;  
    }
    

提交回复
热议问题