带头节点的单向链表反转

package com.qcby.bilbil;

/**
 * @author HuangHaiyang
 * @date 2020/07/08
 * @description: description
 * @version: 1.0.0
 */
public class ReversalList {

    private Node head=new Node(0,null);//带头节点

    private Integer size=0;

    public void add(Node node){
        Node temp=head;

        while (temp.next!=null){
            if(temp.next.val.equals(node.val)){
                throw new RuntimeException("已存在");
            }
            temp=temp.next;
        }
        temp.next=node;
        size++;
    }

    public void show(){
        Node temp=head.next;
        while (temp!=null){
            System.out.println(temp);
            temp=temp.next;
        }
    }

    public void Reverse(){
        Node current=head.next;//辅助指针,遍历链表

        Node next=head.next;//指向当前节点的下一个节点

        Node resHead=new Node(0);//新的头

        while (next!=null){
            next=current.next;//暂时保存下一个节点
            current.next=resHead.next;//将当前节点的next 指向 新的头的后面的内容
            resHead.next=current;// 将当前节点插入到 新的头的后面 ,头插法
            current=next;//向后遍历
        }
        head.next=resHead.next;
    }

    public static void main(String[] args) {
        ReversalList reversalList=new ReversalList();
        for (int i = 1; i <=10 ; i++) {
            reversalList.add(new Node(i));
        }
        reversalList.show();
        reversalList.Reverse();
        System.out.println("===============================");
        reversalList.show();
    }

}

class Node{
    public Integer val;
    public Node next;

    public Node() {
    }

    public Node(Integer val, Node next) {
        this.val = val;
        this.next = next;
    }
    public Node(Integer val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值