Reversing a singly linked list iteratively

后端 未结 7 1184
情话喂你
情话喂你 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:31

    Modifying the Node Class

    u can override toString method in Node class to input any data

    public class Node { public Node node; private int data; Node(int data) { this.data = data; } @Override public String toString() { return this.data+""; }

    0 讨论(0)
  • 2021-01-01 08:36

    How about this:

    public void invert() {
        if (head != null) {
            for (Node<E> tail = head.getNext(); tail != null; ) {
                Node<E> nextTail = tail.getNext();
                tail.setNext(head);
                head = tail;
                tail = nextTail;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 08:37

    Works with this implementation of LinkedList: https://stackoverflow.com/a/25311/234307

    public void reverse() {
    
        Link previous = first;
        Link currentLink = first.nextLink;
        first.nextLink = null;
    
        while(currentLink != null) {        
    
            Link realNextLink = currentLink.nextLink;
            currentLink.nextLink = previous;                        
            previous = currentLink; 
            first = currentLink;    
            currentLink = realNextLink;
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-01 08:39
    public void reverse(){
    
        Node middle = head;
        Node last = head;
        Node first = null;
    
        while(last != null){
    
            middle = last;
            last = last.next;
            middle.next = first;
            first = middle;
        }
    
        head = middle;
    }
    
    0 讨论(0)
  • 2021-01-01 08:43

    Using a self-contained implementation, i.e. the List is represented by the head Node:

    public class Node<E>
    {
        Node<E> next;
        E value;
    
        public Node(E value, Node<E> next)
        {
            this.value = value;
            this.next = next;
        }
    
        public Node<E> reverse()
        {
            Node<E> head = null;
            Node<E> current = this;
            while (current != null) {
                Node<E> save = current;
                current = current.next;
                save.next = head;
                head = save;
            }
            return head;
        }
    }
    
    0 讨论(0)
  • 2021-01-01 08:43
    public void invert() {  
      if (first == null) return;  
      Node<E> prev = null;  
      for ( Node<E> next = first.next; next != null; next = first.next) {  
        first.next = prev;  
        prev = first;  
        first = next;  
      }  
      first.next = prev;  
    }
    
    0 讨论(0)
提交回复
热议问题