输入链表,反转链表后,输出新的链表标题。
递归法
公共类revnnode {
公共静态类节点{
公共收入值;
公共节点下一个节点;
公共插入获取值
返回值;
}
公共语音设置(intvalue ) {
this.value=value;
}
公共节点获取下一个节点
返回下一个节点;
}
publicvoidsetnextnode (节点下一节)。
this.nextNode=nextNode;
}
公共节点(空闲) {
this.value=value;
}
}
//*
*翻转操作方法1递归实现:从最后一个节点开始,在弹堆栈的过程中按顺序替换指针。
*
* @param head
* @return
*/
publicstaticnodereverse1(节点头) {
if (head==null|| head.next node==null ) ) () ) ) ) ) ) ) ) )。
返回头;
节点时间=head.next node;
节点new head=reverse1(head.next node;
temp.nextNode=head;
head.nextNode=null;
返回新头;
}
//*
*反转操作方法2 :在链表遍历过程中调换指针顺序
* @param node
* @return
*/
publicstaticnodereverse2(节点节点) {
节点pre=null;
节点下一步=null;
wile (节点!=空) {
next=node.nextNode;
node.nextNode=pre;
pre=node;
节点=next;
}
返回前;
}
publicstaticvoidmain (字符串[ ] args ) {
节点头=新节点(0;
节点1=新节点(1;
节点2=新节点(2;
节点3=新节点(3;
head.setnextnode(node1;
节点1.set next node (node 2;
节点2.set next node (node3);
//打印反转前的链表
节点h=head;
空!=h (
system.out.print(h.getvalue () ');
h=h.getNextNode (;
}
//调用反转方法1
system.out.println ('n * * * * * * * * * reverse1* * * * * * * * * * * * * * * * () () ) ) ) )
头=reverse1(head );
//打印反转后的结果
空!=head ) {
system.out.print;
head=head.getNextNode (;
}
//调用翻转方法2
(system.out.println ((n * * * * * * * * * reverse2* * * * * * * * * * * * * * * ' ) ) ) ) ) )
head=reverse2(head );
//打印反转后的结果
空!=head ) {
system.out.print;
head=head.getNextNode (;
}
}
}