首页 > 编程知识 正文

反转单向链表java,手写代码反转链表java

时间:2023-05-06 15:07:36 阅读:33490 作者:1785

基本思想定义了两个空指针(pre和next ),如果头指针指向的值不为空,则在next中定义头节点的下一个节点的值(head.next ),pre指针的值为head.next,头节点的值为pre,next 如果head等于空,则将pre指针指向的值指定给head会反转链表

图像分析如图所示,输入1-5的链表

head与空不一样,进行反转操作

head等于空,为head分配pre值,链表完成反转。

代码/** *当前节点类,堆内存中包含节点* /公共类列表{公共intvalue; //数据域公共列表下一步; //下一个节点的地址域公共列表(intvalue ) { this.value=value; //链表的管理类public class link list { listnode head=null; //写制作链表的方法。 链表的插入方法//末尾插入法publicvoidinsert(intvalue ) (listnodelistnode=newlistnode ) (value ); if(head==null ) { head=listNode; 返回; } ListNode tempNode=head; wile(tempnode.next!=null}{tempnode=tempnode.next; } tempNode.next=listNode; //输出链表的值public void printLink () /,定义右侧指向链表的第一个节点ListNode tempNode=head。 wile (模板!=null ) system.out.println (tempnode.value ); tempNode=tempNode.next; (//链表public void fz ) ) {ListNode pre=null; listnode next=空; wile (头!=null}{next=head.next; head.next=pre; pre=head; head=next; (}head=pre; { public class main {实现publicstaticvoidmain (字符串[ ] args ) {LinkList linkList=new LinkList ); linklist.insert(5; linklist.insert(7; linklist.insert(8; linkList.insert(9(); System.out.println ('反转前); linkList.printLink (; linkList.fz (; 系统. out.println (翻转后); linkList.printLink (; }结果

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。