天天看点

单链表反转操作示例分享

下文是笔者编写的单链表反转操作

package com.java265.algorithm;

/*
 * 单项链表的反转操作
 * */
public class LinkedListReverse {


    static LinkedList head;

    /**
     * 初始化链表
     */
    static void initLinkedList() {

        head = new LinkedList(1);
        head.next = new LinkedList(2);
        head.next.next = new LinkedList(3);
        head.next.next.next = new LinkedList(4);
        head.next.next.next.next = new LinkedList(5);

    }

    /*
     * 打印链表
     */
    static void printLinkedList() {
        LinkedList cur = head;
        while (cur != null) {
            System.out.println(cur.value);
            cur = cur.next;
        }
    }

    /**
     * 链表反转
     */
    static void LinkedListResver() {
        LinkedList cur = head.next;
        LinkedList t;
        while (cur != null) {
            t = head;
            t.next = (t.next == cur) ? null : t.next; //此处需特别注意,否则会形成一个回路
            head = cur;
            cur = head.next;
            head.next = t;

        }
    }

    public static void main(String[] args) {
        initLinkedList();
        printLinkedList();
        System.out.println("=================");
        // 反转链表
        LinkedListResver();
        printLinkedList();
    }


}

class LinkedList {
    public int value;
    public LinkedList next;

    public LinkedList(int value) {
        this.value = value;
    }
}      

继续阅读