欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

带头节点的单向链表反转

程序员文章站 2022-03-01 19:50:15
...
package LinkedListReverse;

/**
 * @author Mzh
 * @date 2020-07-09 09:22
 * @description:mzh
 * @version: 1
 */

public class ReverseList {
    private Node head =new Node(0,null);
    private Integer size=0;

    public void add(Node node) throws Exception {
        Node tmp=head;
        while(head.next!=null){
            if (tmp.next.val.equals(node.val)){
                throw new Exception("重复");
            }
            tmp= tmp.next;
        }
        tmp.next=node;
        size++;
    }
    public void show(){
        Node tmp=head;
        while (tmp!=null){
            System.out.println(tmp);
            tmp=tmp.next;
        }
    }
    public void reverse(){
        Node cur=head.next;
        Node tmp=head.next;
        Node newHead=new Node(0,null);
        while(tmp!=null){
            tmp=cur.next;
            cur.next=newHead.next;//就是先把新数组结到当前,当前节点在最前面了
            newHead.next=cur;//赋值回newhead,相当于在newhead和已经添加的到newhead元素之间,取添加新的
//            cur=cur.next;//这是不行的,因为cur已经被手边到新的list
            cur=tmp;//这就是提前保存tmp的作用。
        }

        head.next=newHead.next;
    }

    public static void main(String[] args) {
        ReverseList reverseList=new ReverseList();
        for (int i = 1; i <=10 ; i++) {
            try {
                reverseList.add(new Node(i));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        reverseList.show();
        reverseList.reverse();
        System.out.println("===============================");
        reverseList.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 +
                '}';
    }
}