zoukankan      html  css  js  c++  java
  • java单向链表的简单实现

    package com.fy.api.server.demo2;


    public class LkList {

    private Node head;

    private Node current;

    public class Node {

    public int data;

    public Node next;

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

    public void add (Node node) {
    if(head == null) {
    head = node;
    current = head;
    }
    if (current.next == null) {
    current.next = node;
    } else {
    current = current.next;
    current.add(node);

    }
    }

    }

    public void addNode (Node node) {
    if (node == null) {
    System.out.println("can't add a null element!");
    return;
    }
    current = head;
    if (head == null) {
    //System.out.println("throw null pointer exception!");
    head = node;
    return;
    }
    this.current.add(node);
    }

    public void showNodes () {
    this.current = head;
    int count = 0;
    System.out.print("[");
    while(this.current!=null){
    System.out.print(count==0?this.current.data: ","+this.current.data );
    count ++;
    this.current = this.current.next;
    }
    System.out.print("]");
    System.out.println();
    }

    public int len () {
    this.current = head;
    if (this.current == null) {
    return 0;
    }

    if (this.current.next == null) {
    return 1;
    }
    int len = 1;
    while (this.current.next !=null) {
    len++;
    this.current = this.current.next;
    }
    return len;
    }

    public void deleteNode (int index) {
    if (index <0 || index>=this.len()) {
    System.out.println("exception outof list bounds!");
    return;
    }

    if (index == 0) {
    head = head.next;
    if (head!=null) {
    current = head;
    }
    }

    int len = 1;
    Node tmp = head;
    while (tmp.next != null) {
    if (index == len++) {
    tmp.next = tmp.next.next;
    return;
    }
    tmp = tmp.next;
    }
    }

    public static void main (String []args) {
    LkList lk = new LkList();
    Node head = lk.new Node(1);
    lk.addNode(head);
    lk.addNode(lk.new Node(2));
    lk.addNode(lk.new Node(3));
    lk.addNode(lk.new Node(4));
    System.out.println(lk.len());
    lk.showNodes();
    lk.deleteNode(0);
    lk.showNodes();
    lk.addNode(lk.new Node(5));
    lk.showNodes();
    lk.deleteNode(3);;
    lk.showNodes();
    System.out.println(lk.len());
    }

    }

  • 相关阅读:
    丸内の霊 補充4
    丸内の霊 補充3
    丸内の霊 補充2
    N1 语法单词
    完全掌握1级日本与能力考试语法问题对策
    丸の内の霊 補充1
    丸内の霊 8
    丸内の霊   7
    丸内の霊  6
    丸の内の霊 6
  • 原文地址:https://www.cnblogs.com/playburst/p/7998128.html
Copyright © 2011-2022 走看看