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

不带头节点的单链表及其基本操作(Java实现)

程序员文章站 2024-03-23 14:45:58
...
package lwh.linearlist.linklist;

public class Node {

    protected int e;
    protected Node next;

    public Node(){};

    public Node(int e){
        this.e = e;
    }

    public Node(int e, Node next){
        this.e = e;
        this.next = next;
    }
}
package lwh.linearlist.linklist;

import java.util.Scanner;

//不带头节点的单链表
public class LinkList {

    private Node head;

    public LinkList(){
        head = null;
    }

    //头插法建立单链表
    public void createListHead(){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int num = sc.nextInt();
            if(num != 99){
                Node node = new Node(num);
                node.next = head;
                head = node;
            }else{
                break;
            }
        }
    }

    //递归删除不带头节点单链表中所有值为x的节点
    public void delete(int x){
        Node q = head;
        Node p = q;
        while(q != null && x != q.e){
            p = q;
            q = q.next;
        }
        if(q == head){
            head = q.next;
            q.next = null;
            q = null;
            delete(x);
        }else if(q != null){
            p.next = q.next;
            q.next = null;
            q = null;
            delete(x);
        }else{
            return;
        }
    }

    public void print() {
        if(head == null){
            System.out.println("No num");
            return;
        }
        System.out.print("[");
        for(Node node = head; node != null; node = node.next){
            if(node.next != null)
                System.out.print(node.e + ",");
            else
                System.out.print(node.e + "]");
        }
        System.out.println();
    }
}
相关标签: java 单链表