单链表的转置 (反转)
普通方法 通过循环与临时变量来转置 优点是节省内存开销
public void commonReverse(){
Node curr = head;
Node reve = null;
while(curr != null){
Node temp = curr;
curr = curr.next;
temp.next = reve;
reve = temp;
}
}
解析:当list = a1 a2 a3 a4 时
运算方式
第一轮:curr = a1 ; temp = a1 ; curr = a2 ; a1.next = null ; reve = a1;
第二轮:curr = a2 ; temp = a2 ; curr = a3 ; a2.next = a1 ; reve = a2;
第三轮:curr = a3 ; temp = a3 ; curr = a4 ; a3.next = a2 ; reve = a3;
第四轮:curr = a4 ; temp = a4 ; curr = null; a4.next = a3;reve = a4;
消耗内存最小 也容易理解
递归算法
public Node recursionReverse(Node head){
if(head == null || head.next == null){
return head;
}
Node tail = recursionReverse(head);
head.next.next = head;
head.next = null;
return tail;
}
解析:当list = a1 a2 a3 a4 时
运算方式
第一轮 : head = a1; head.next.next = head; head.next =null; 两个方法压入栈中 其中head = a1;
第二轮 : head = a2; head.next.next = head;head.next =null; 两个方法压入栈中 其中head = a2;
第三轮 : head = a3; head.next.next = head;head.next =null; 两个方法压入栈中 其中head = a3;
第四轮 : head = a4; 返回方法栈 取出第三轮剩余方法执行
第三轮剩余方法:head = a3 ; a3.next = a4 ; a4.next = a3; a3.next = null;
第二轮剩余方法:head = a2 ; a2.next = a3 ; a3.next = a2; a2.next = null;
第一轮剩余方法:head = a1 ; a1.next = a2 ; a2.next = a1; a1.next = null;
完毕