定义
- 线性表的链式存储结构的特点是用一组任意的存储单元存储线性表中的数据元素,这组存储单元可以存放在内存中未被占用的任意位置。
- 相比顺序存储结构,链式存储结构中,除了需要存储数据元素信息之外,还需要存储它的后继元素的存储地址(指针)。
- 数据域:存储数据元素信息的域,指针域:存储直接后继位置的域。指针域中存储的信息成为指针或链。这两部分信息组成数据元素成为存储映像,成为结点(Node)。
-
实现:首先定义节点
-
package linkedList; /* 首先定义节点:包括数据域data、指针域next */ public class Node <T> { private T data; //定义节点数据 public Node next; //定义节点指针 public Node(T data,Node next){ this.data=data; this.next=next; } public T getData(){ return data; } public void setData(T data){ this.data=data; } }
-
其次,基于节点,实现单链表主体结构及其相应功能函数:
-
package linkedList; /* 基于节点定义链表 */ public class linkedList<T> { private Node head; //定义头结点 private Node tail; //定义尾节点 private int size; //定义链表尺寸 public linkedList(){ head=null; tail=null; } //获取链表长度 public int getLength(){ return size; } //判断链表是否为空 public boolean isEmpty(){ return size==0; } //清空链表 public void clear(){ head=null; tail=null; size=0; } //通过索引获取节点 public Node getNodeByIndex(int index){ if(index<0||index>size-1){ throw new IndexOutOfBoundsException("索引越界"); } Node node=head; for(int i=0;i<size;i++,node=node.next){ if(i==index){ return node; } } return null; } //头插入 public void addAtHead(T element){ head=new Node<T>(element,head); //如果是空链表则让尾指针指向头指针 if(tail==null){ tail=head; } size++; } //尾插入 public void addTtTail(T element){ //如果表为空 if(head==null){ head=new Node<T>(element,null); tail=head; }else{ Node node=new Node <T>(element,null); tail.next=node; tail=node; } size++; } //中间插入 public void insert(T element,int index){ if (index<0||index>size-1){ throw new IndexOutOfBoundsException("索引越界"); } if(index==0){ addAtHead(element); }else if(index>0&&index<size-1){ Node nextNode=null; Node InsertNode=new Node<T>(element,nextNode); nextNode=getNodeByIndex(index); Node preNode=getNodeByIndex(index-1); preNode.next=InsertNode; InsertNode.next=nextNode; size++; }else { addTtTail(element); } } //删除节点 public void delete(int index){ if(index<0||index>size-1){ throw new IndexOutOfBoundsException("索引越界"); } int flag=index-1; Node node=getNodeByIndex(index); if(flag<0){ //flag小于0说明删除的是头结点 head=head.next; node=null; }else{ Node preNode=getNodeByIndex(index-1); preNode.next=node.next; //如果删除的是尾节点,则尾节点向前移动一位 if(index==size-1){ tail=preNode; } size--; } } public String toString() { StringBuilder sb=new StringBuilder(); Node node=head; for(int i=0;i<size;i++,node=node.next) { sb=sb.append(node.getData()+" "); } return sb+""; } public static void main(String[] args){ linkedList linkedList=new linkedList(); linkedList.addAtHead(2); linkedList.addAtHead(3); linkedList.addAtHead(6); System.out.println(linkedList); } }
-