package链表逆置;
publicinterfaceLinkedListInterface{
publicvoidaddNode(intdata);
publicvoiddisplay1();
publicvoiddisplay2();
publicvoidreserve();
}
package链表逆置;
importjava.util.Stack;
publicclassLinkedListDemoimplementsLinkedListInterface{
publicNodehead;
publicLinkedListDemo(){
this.head=newNode();
if(this.head==null){
System.out.println("头指针创建失败!");
return;
}
this.head.next=null;
}
publicvoidaddNode(intdata){
Nodenode=newNode(data);
Nodep=this.head;
if(this.head.next==null){
this.head.next=node;
}else{
while(p.next!=null){
p=p.next;
}
p.next=node;
}
}
publicvoiddisplay1(){
Nodep=this.head.next;
while(p!=null){
System.out.print(p.data+"");
p=p.next;
}
System.out.println();
}
//01修改链表的指针指向
publicNodegetHeadReserve(){
Noden=this.head.next;
this.head=null;
while(n!=null){
Nodem=n;
n=n.next;
m.next=head;
head=m;
}
returnthis.head;
}
publicvoiddisplay2(){
Nodep=this.head;
while(p!=null){
System.out.print(p.data+"");
p=p.next;
}
System.out.println();
}
//02利用栈实现倒序输出
@Override
publicvoidreserve(){
Stack<Node>stack=newStack<Node>();
Nodep=this.head.next;
while(p!=null){
stack.push(p);
p=p.next;
}
while(!stack.isEmpty()){
System.out.print(stack.pop().data+"");
}
}
//03利用递归
publicvoiddiguiReserve(Nodenode){
if(node.next!=null){
diguiReserve(node.next);
}
System.out.print(node.data+"");
}
}
package链表逆置;
publicclassNode{
publicintdata;
publicNodenext;
publicNode(){
}
publicNode(intdata){
this.data=data;
this.next=null;
}
}
package链表逆置;
publicclassTestLinked{
publicstaticvoidmain(String[]args){
LinkedListDemolinkedListDemo=newLinkedListDemo();
linkedListDemo.addNode(1);
linkedListDemo.addNode(2);
linkedListDemo.addNode(3);
linkedListDemo.addNode(4);
linkedListDemo.display1();
//linkedListDemo.getHeadReserve();
//linkedListDemo.display2();
linkedListDemo.diguiReserve(linkedListDemo.head.next);
//linkedListDemo.reserve();
}
}