链表自定义队列

来源:互联网 发布:电脑看书软件阅读器 编辑:程序博客网 时间:2024/05/02 02:09

一:链表自定义队列

1:单向链表

数组是很有用的数据结构,但是有两个局限性:

(1)若改变数据的大小就需要创建一个新数据并从原数组中拷贝所有数据至新数组

(2)数组数据在内存中依次连续存储,向数据中插入一项要移动数组中其他数据

链表数据结构是使用指针(即引用)将存储数据元素的那些单元依次串联在一起

这种方法避免了在数组中连续的单元存储元素的缺点,因而在插入或者删除时不再需要移动元素来腾出空间或填补空缺。

java中并没有指针。

链表定义逻辑:需要作出的改变就是在每个单元中设置指针来表示表中元素之间 逻辑关系(前还是后)。

定义链表节点:数据域和指针域(引用)


单向链表特点:

单链表的一个重要特性是只能通过前驱节点找到后续节点

    因此在单链表中进行查找操作,只能从链表的首节点开始,通过每个节点的next引用来依次访问链表中的每个节点以完成相应的查找操作。而而无法从后续节点找到前驱节点。

单链表节点的设计:

定义Node节点类,并声明数据域属性和下一个节点指针属性。

通常在单链表的最前面添加一个哑元节点,也成为头节点(Head)

注意:头节点有别于真正的首节点,头节点中不存储任何实质的数据对象,其next通常指向0位的元素。


/* * 结点类 * */public class Node {//定义数据域private String value;//指针域private Node next;//定义方法public Node(String value){this.value = value;}public String getValue(){return value;}public void setValue(String value){this.value = value;}public Node getNext(){return next;}public void setNext(Node next){this.next = next;}}

/* * 链表队列 * */public class LinkNodeList {private Node head;//添加public void add(String value){//添加数据Node node = new Node(value);//判断头是否为空if(head==null){head = node;}else{Node newNode = head;//先找到最后一个结点while(newNode.getNext()!=null){newNode = newNode.getNext();}//把当前结点,给最后一个结点的下一个引用域newNode.setNext(node);}}//插入public void insert(String value,int index){//首先,验证参数是否正确,进行异常处理if(index<0||index>=size()){try {throw new Exception("索引越界");} catch (Exception e) {e.printStackTrace();}}else{//封装结点Node node = new Node(value);if(index==0){//把当前结点的下一个结点赋值给头结点node.setNext(head);head=node;return;}int count = 0;Node newNode = head;//先找到最后一个结点while(count!=(index-1)){newNode = newNode.getNext();count++;}//再获取当前结点的下一个结点Node nextNode = newNode.getNext();//新结点插入两个结点之间newNode.setNext(node);node.setNext(nextNode);}}//删除public void delete(int index){}//获取大小public int size(){//定义计数器int count = 0;//头是否为空if(head==null){return count;}else{Node newNode = head;count++;// 先找到最后一个结点while (newNode.getNext() != null) {newNode = newNode.getNext();count++;}return count;}}//查找public String get(int index){if(index<0||index>=size()){try {throw new Exception("索引越界");} catch (Exception e) {e.printStackTrace();}return null;}else{int count = 0;Node newNode = head;while(count!=index){newNode = newNode.getNext();count++;}return newNode.getValue();}}//更新public void update(int index,String value){}}

public class Test {public static void main(String[] args){LinkNodeList list = new LinkNodeList();list.add("qqq");list.add("aaa");list.add("sss");list.add("ddd");list.add("aaa");list.add("sss");    list.add("eee");list.insert("qqq",2);System.out.println(list.size());for(int i=0;i<list.size();i++){System.out.println(list.get(i));}}}



0 0
原创粉丝点击