单链表反转

package com.bittech.Linked;

public class MySingleListImpl {

    class Node {

        private int data;
        private Node next;

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

    private Node head;
    public MySingleListImpl() {
        this.head = null;
    }

	//头插
    public void addFirst(int data) {

        Node node = new Node(data);
        if (this.head == null) {
            this.head = node;
        }else {
            node.next = this.head;
            this.head = node;
        }
    }

	//尾插
    public void addLast(int data) {

        Node node = new Node(data);
        if (this.head == null) {
            this.head = node;
        }else {
            Node cur = this.head;
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
        }
    }

	//打印单链表
    public void display() {

        Node cur = this.head;
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    //反转一个单链表
    public Node reverseList() {
		
        Node reverseHead = null;//反转后的新结点
        Node prev = null;//需要反转的节点的前驱
        Node cur = this.head;//当前需要反转的节点

        while (cur != null) {
            Node curNext = cur.next;
            if (curNext == null) {//说明cur已经是最后一个节点了,反转后就是第一个节点
                reverseHead = cur;
            }
            cur.next = prev;//让cur的指针域指向prev,逆置
            prev = cur;
            cur = curNext;
        }
        return reverseHead;
    }

    //打印翻转后的链表(此时不能再用dispaly了,因为链表的头结点已经发生了改变)
    public void show(Node newHead) {

        Node cur = newHead;
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
        System.out.println();
    }
}
package com.bittech.Linked;

public class Test {

    public static void main(String[] args) {

        MySingleListImpl list = new MySingleListImpl();

        list.addFirst(134);
        list.addFirst(20);
        list.addFirst(35);
        list.addLast(10);
        list.addLast(999);
        list.addLast(7);
        System.out.print("原链表:");
        list.display();

        MySingleListImpl.Node newNode = list.reverseList();
        System.out.print("反转后的链表:");
        list.show(newNode);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值