03链表反转-头插法

/**
 * 定义一个单链表
 */
class Node {
    //变量
    private int record;
    //指向下一个对象
    private Node nextNode;
    public Node(int record) {
        super();
        this.record = record;
    }
    public int getRecord() {
        return record;
    }
    public void setRecord(int record) {
        this.record = record;
    }
    public Node getNextNode() {
        return nextNode;
    }
    public void setNextNode(Node nextNode) {
        this.nextNode = nextNode;
    }
}
/*
 *两种方式实现单链表的反转(递归、普通)
 *新手强烈建议旁边拿着纸和笔跟着代码画图(便于理解)
 */
public class SingleLinkReverse {
    /**
     * 递归,在反转当前节点之前先反转后续节点
     */
    public static Node reverse(Node head) {
        if (null == head || null == head.getNextNode()) {
            return head;
        }
        Node reversedHead = reverse(head.getNextNode());
        head.getNextNode().setNextNode(head);
        head.setNextNode(null);
        return reversedHead;
    }
    /**
     * 遍历,将当前节点的下一个节点缓存后更改当前节点指针
     *
     */
    public static Node reverse2(Node head) {
        if (null == head) {
            return head;
        }
        Node pre = head;
        Node cur = head.getNextNode();
        Node next;
        while (null != cur) {
            next = cur.getNextNode();
            cur.setNextNode(pre);//cur节点指向pre
            pre = cur;//pre移动到cur(即当前节点有两个名字,pre和cur)
            cur = next;//cur移动到 next(即当前节点有两个名字,next和cur)
        }
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
        head.setNextNode(null);//将head下一个节点置空,让head恢复初始
        head = pre;//把pre赋给head,因为此时pre是反转后的头节点
        return head;
    }
    public static void main(String[] args) {
        Node head = new Node(0);
        Node tmp = null;
        Node cur = null;
// 构造一个长度为10的链表,保存头节点对象head
        for (int i = 1; i < 10; i++) {
            tmp = new Node(i);
            if (1 == i) {
                head.setNextNode(tmp);//将Node(1)设置为head后一个节点
            } else {
                cur.setNextNode(tmp);
            }
            cur = tmp;//刚开始cur表示Node(1)节点,后来让cur后移
        }
//打印反转前的链表
        //Node h = head;临时变量h遍历完后会指向链表末尾,但是head任然指向表头,可用于下次遍历
        Node h = head;
        while (null != h) {
            System.out.print(h.getRecord() + " ");
            h = h.getNextNode();
        }
//调用反转方法
        head = reverse2(head);
        System.out.println("\n**************************");
//打印反转后的结果
        while (null != head) {
            System.out.print(head.getRecord() + " ");
            head = head.getNextNode();
        }
    }
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值