单向链表的反转

这个有点困扰我,记录一下。

直接记录代码和注释吧。

package com.fazhuan;

//链表结点类
class Node {
    Node next = null;
    int data;

    public Node(int data) {
        this.data = data;
    }

}

public class Main {

    /**
     * 
     * @param head
     *            :链表反转以前的head
     * @return 返回链表反转以后的head
     */
    private static Node ReverseIteratively(Node head) {
        // 初始化反转后的头
        Node root = head;
        // 初始化当前节点为原始链表头
        Node cur = head;
        // 初始化当前节点的上一个节点
        Node pre = null;

        // 循环检测当前节点是否为null
        while (null != cur) {
            // 保存当前节点的下一个节点
            Node tmp = cur.next;

            if (null == tmp) {// 如果当前节点的下一个节点是null,就表示到了链表末端
                root = cur;// 反转以后链表的头找到了
            }

            // 当前链表位置的下一个指针指向上一个位置
            cur.next = pre;

            // 更新上一个位置和当前位置,便于下一次循环
            // pre永远指向已经完成反转链表的最后一个节点
            // cur永远指向未完成反转链表的第一个节点
            pre = cur;
            cur = tmp;
        }
        return root;
    }

    public static void main(String[] args) {
        Node head = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        head.next = node1;
        node1.next = node2;
        node2.next = node3;

        // 打印反转前的链表
        Node h = head;
        while (null != h) {
            System.out.print(h.data + " ");
            h = h.next;
        }

        Node root = ReverseIteratively(head);

        System.out.println("\n**********");

        // 打印反转后的链表
        while (null != root) {
            System.out.print(root.data + " ");
            root = root.next;
        }

    }
}

完!

猜你喜欢

转载自blog.csdn.net/qq_36006553/article/details/73774211