1. 程式人生 > >反轉單向連結串列和反轉雙向連結串列

反轉單向連結串列和反轉雙向連結串列

問題描述:反轉單向連結串列和雙向連結串列
要求:如果連結串列長度為N,時間複雜度要求為O(N),額外的空間複雜度要求為O(1)

思路一:首先想到了棧的特點

 public class Node{
        public int value;
        public Node next;
        public Node(int data){
            this.value=data;
        }
    }

    public Node reverseListStack(Node head){
        Stack<Node> stack=new
Stack<Node>(); while(head!=null){ stack.push(head); head=head.next; } return stack.peek(); }

此時的時間複雜度為O(N),空間複雜度也是O(N)。不滿足空間複雜度的要求

思路二:直接移位

 public class Node{
        public int value;
        public Node next;
        public Node(int data){
            this
.value=data; } } public Node reverseList(Node head){ Node pre=null; Node next=null while(head!=null){ next=head.next; head.next=pre; pre=head; head=next; } return pre; }

以上時間複雜度為O(N),輔助的空間複雜度為O(1),滿足要求

反轉雙向連結串列,藉助上面的思路,程式碼如下:

package QuestionTest;

/**
 * Created by L_kanglin on 2017/3/17.
 * 反轉雙向連結串列
 */
public class Test9 {
    public class DoubleNode{
        public int value;
        public DoubleNode next;
        public DoubleNode last;

        public DoubleNode(int data){
            this.value=data;
        }
    }
    public DoubleNode reverseList(DoubleNode head){
        DoubleNode pre = null;
        DoubleNode next = null;
        while(head!=null){
            next = head.next;
            head.next=pre;
            head.last=next;
            pre=head;
            head=next;
        }
        return pre;
    }
}