【题目】
分别实现反转单向链表和反转双向链表的函数。
【要求】
如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)。
【代码】
//反转单向链表
public Node reverseList(Node head){
Node pre=null;//当前结点的前结点
Node next=null;//当前结点的后结点
while(head!=null){//从左到右,依次把->变为<-
next=head.next;
head.next=pre;//当前结点指向前面的结点
pre=head;//pre结点右移
head=next;//head结点右移
}
return pre;
}
//反转双向链表
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;//pre右移
head=next;//head右移
}
return pre;
}