问题描述:反转单向链表和双向链表
要求:如果链表长度为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;
}
}