6、通过数组创建单链表,并反转单链表

步骤
  • 1、尾部插入法创建链表
  • 2、自定义上一个节点、当前节点、下一个节点,遍历反转链表,主要是把当前节点的下一个节点设置为当前节点的上一个节点;
public class ReverseLinkd {

    private static Node head;
    private static Node tail;

    public static void main(String[] args) {
        String[] dataArray = {"1", "2", "3", "4", "5", "6", "7"};
        for(int i = 0; i< dataArray.length; i++) {
            createLinked(dataArray[i]);
        }
        System.out.println("---------------原链表---------------");
        printAll(head);

        System.out.println("---------------反转后链表---------------");
        printAll(reverse(head));

    }
    //链表反转方法
    public static Node reverse(Node node) {
        if(node == null) {
            System.out.println("空链表");
            return null;
        } else if(node.next == null) {
            System.out.println("链表只有一个节点");
            return node;
        } else {
            Node pre = null;
            Node next = null;
            Node cur = node;
            while(cur != null) {
                //记录下一个要操作的节点
                next = cur.next;
                //当前节点的下一个节点为当前节点的上一个节点,实现反转
                cur.next = pre;
                //上一个节点和当前节点全部后移
                pre = cur;
                cur = next;
            }
            return pre;
        }
    }

    //创建一个单链表,尾部插入法
    public static void createLinked(String nodeData) {
        Node node = new Node(nodeData);
        if(head == null) {
            head = node;
            tail = head;
        } else {
            tail.next = node;
            tail = node;
        }
    }

    //打印链表
    public static void printAll(Node node) {
        if(node == null) {
            System.out.println("空链表");
        } else {
            while(node != null) {
                System.out.print(node.getData() + "-->");
                node = node.next;
            }
        }
        System.out.println();
    }


    //定义单链表
    static class Node{
        public String data;
        public Node next;

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

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值