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

    xiaoxiao2022-07-14  158

    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),就只是遍历一下单链表。

    最新回复(0)