逆序单链表 时间复杂度O(n)

public class Node{
    int value;
    Node next;
    public Node(int value){
      this.value = value;    
    }
    
    //这个反转单链表这样想象,把原先链表的节点从头取出来接在另一个新链表上
    public Node reverse(Node head){
      if(root == null){
         return null;
      }
      Node pre = null;//pre可以认为是不断构造的反转链表的头结点
      Node next = null;//next用来保存next的值
      while(head != null){//这里直接修改head,这个head用不着保存了
          next = head.next;
          head.next = pre;
          pre = head;
          head = next;
      }
      return pre;
      
}

时间复杂度就是O(n),就只是遍历一下单链表。

猜你喜欢

转载自blog.csdn.net/shen19960603/article/details/90489814
今日推荐