如何实现链表的逆序

不想你离开。 提交于 2020-03-09 00:32:28
package com.example.lib;

public class LianBiao1 {
    public static void main(String[] args) {

        LNode head=new LNode();
        LNode next=null;
        for(int i=1;i<=7;i++){
            LNode cur=new LNode();
            cur.data=i;
            if(head.next==null){
                head.next=cur;
                next=cur;
            }else {
                next.next=cur;
                next=cur;
            }
        }
        next.next=null;
        Reverse(head);

        printNode(head);
    }

    public static void printNode(LNode head){
        StringBuffer buffer=new StringBuffer();
        LNode cur=head.next;
        while (cur!=null){
            buffer.append(" "+cur.data);
            cur=cur.next;
        }
        System.out.println(buffer.toString()+"\n");
    }

    public static void Reverse(LNode head){
    //head-> 1 ->2 ->3 -> 4 ->5 -> 6 ->7

        // head-> 7 ->6-> 5 -> 4 ->3 -> 2 ->1

        if(head==null||head.next==null){
            return;
        }

        //把首结点指向尾结点
        LNode pre,cur,next;
        cur=head.next;//1
        next=cur.next;//2
        cur.next=null;

        pre=cur;//1
        cur=next;//2
       
        while (cur!=null){
            next=cur.next;//获取当前结点的下一个结点
            cur.next=pre;//将当前结点的前一个结点给当前结点

            if(next==null)//如果是最后一个结点,则直接结束
                break;
            pre = cur;//2
            cur = next;//3

        }

        head.next=cur;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!