LinkList其实没那么难

来源:互联网 发布:大卫泰勒增高 知乎 编辑:程序博客网 时间:2024/04/29 07:35

      虽然理论上对链表的理解很到位,但是从代码实现上每次都无从下手。

      链表是由一个个结点组成  定义一个结点类

package com.Techck.Linklist;
/**
* 链表节点对象
* @author Administrator
*
*/
public class Node {
/**
* 数据域属性
*/
private String date;
/**
* 下一个引用域属性
*/
private Node next;
 /**
* 构造函数,根据节点数据和下一个节点的引用
* @param date 数据
* @param next 下一个节点的引用
*/
public Node(String date, Node next) {
super();
this.date = date;
this.next = next;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}

      然后就是定义一个链表类,这里我是为了方便,写了一个链表接口,然后去链表类去实现它

package com.Techck.Linklist;

public class LinkList implements LinkListInterface {
 /**
  * 定义头节点
  */
 public Node head;

 @Override
 public int size() {
  int count = 0;
  // 判断当前首节点是否为空
  if (head == null) {
   return count;
  } else {
   // 如果头节点存在,则累加一次计数器
   count++;
   // 获取下一个节点
   Node node = head.getNext();
   while (node != null) {
    count++;
    node = node.getNext();
   }
  }
  return count;
 }

 @Override
 public Node get(int index) {
  // 拿到指定索引位置的节点对象
  if (index < 0) {
   // 如果索引位置为负数,打印异常栈
   try {
    throw new Exception("索引不能为负数:" + index);
   } catch (Exception e) {
    e.printStackTrace();
    return null;
   }
  }
  int count = 0;
  // 如果index为0的情况,则直接返回头节点
  if (count == index) {
   return head;
  }
  // 判断索引是不是已经越界
  if (index < size()) {
   // 如果没有越界的情况,获取头节点的下一个节点
   Node node = head.getNext();
   while (node != null) {
    count++;
    if (count == index) {
     return node;
    }
    node = node.getNext();
   }
  } else {
   // 如果索引位置为负数,打印异常栈
   try {
    throw new Exception("索引越界");
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return null;
 }

 @Override
 public void add(String value) {
  // 链表添加节点
  // 创建一个新的节点
  Node node = new Node(value, null);
  if (size() == 0) {
   head = node;
  } else {
   Node node1 = get(size() - 1);
   node1.setNext(node);
  }

 }

 @Override
 public void add(String value, int index) {
  // 链表添加节点
  // 创建一个新的节点
  Node node = new Node(value, null);
  if(head==null){
   head=node;
   return;
  }
  //先拿到当前索引位置的节点
  if(index==0){
   node.setNext(head);
   head = node;
   return;
  }
  Node node_current = get(index);
  Node node_parent = get(index-1);
  node_parent.setNext(node);
  node.setNext(node_current);
 }

 @Override
 public void remove(int index) {
  // TODO Auto-generated method stub

 }
}

      链表里提供各种对链表操作的方法,链表其实就是那么简单

0 0
原创粉丝点击