鏈表逆序-插入法

package com.example.lib;

public class Lianbiao3 {


    public static void main(String[] args) {
        LNode headNode=new LNode();
        LNode preNode=headNode;
        for(int i=1;i<=7;i++){
            LNode node=new LNode();
            node.data=i;
            preNode.next=node;
            preNode=node;
        }

        LianBiao1.printNode(headNode);
    }

    public static void Reverse(LNode head){
        //插入法遠離
        //1、從第二個結點開始
        //head 1 2 3 4 5 6 7
        //把遍歷到到結點插入到head結點後面
        //head 2 1 3 4 5 6 7
        if(head==null||head.next==null){
            return;
        }

        LNode cur=null;//當前結點
        LNode next=null;
        cur=head.next.next;//2結點
        head.next.next=null;//設置第一個結點鏈表爲尾結點

        while (cur!=null){
            next=cur.next;
            cur.next=head.next;
            head.next=cur;
            cur=next;
        }


    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章