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());
    }

    }

  • 相关阅读:
    老罗Android开发视频教程录制计划
    经典游戏源码汇总
    横向TimePicker带三角指示器
    可延长、缩短、拖动图形的画图软件
    手把手教你写android项目@第一期项目——身份证查询创新
    android图表引擎AchartEngine制作柱图
    SharePoint2010如何配置唯一文档ID服务快速生效
    SharePoint客户端对象模型 - .NET托管
    JQuery里如何选择超链接
    如何在SharePointDesigner订制页面里判断用户权限
  • 原文地址:https://www.cnblogs.com/playburst/p/7998128.html
Copyright © 2011-2022 走看看