单链表的反转代码

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/shufangreal/article/details/101212299

单链表的反转代码

单链表反转有2种实现,一种是有头结点的实现,另外一种是无头结点的实现,下面的代码解释了2种情形下的代码实现。

1.利用头结点实现单链表反转

//与下面的代码公用一个LNode结构    
public static void reverse(LNode node, LNode head) {

        if (node == null || node.next == null) return;

        head.next = node;

        LNode i = node;
        LNode j = node.next;


        while (j != null){
            i.next = j.next;
            j.next = head.next;
            head.next = j;

            //i的位置可以不用动
            j = i.next;
        }
    }

2.无头结点的单链表反转

package list;

public class LNode {

        Object data;
    	LNode next;

        public LNode() {
    }

    public LNode(Object data) {
        this.data = data;
        this.next = null;
    }

    @Override
    public String toString() {
        return "LNode{" + "data=" + data + ", next=" + next + '}';
    }
    
    //main方法!!!!
    public static void main(String[] args) {
        LNode l1 = new LNode(1);
        LNode l2 = new LNode(2);
        LNode l3 = new LNode(3);

        l1.next = l2;
        l2.next = l3;

        // => LNode{data=1, next=LNode{data=2, next=LNode{data=3, next=null}}}
        System.out.println(l1);

        reverse(l1);

        // => LNode{data=3, next=LNode{data=2, next=LNode{data=1, next=null}}}
        System.out.println(l3);
    }

    public static void reverse(LNode node) {
        if (node == null || node.next == null) return;

        LNode head = node;
        LNode i = node;
        LNode j = node.next;

        while (j != null) {
            head.next = j.next;
            j.next = i;

            i = j;
            j = head.next;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/shufangreal/article/details/101212299