对于数据结构中最基础的单链表的实现,因为链表不需要连续的内存存储空间,不需要在创建时指定大小,因此比线性表更有优势,对其的插入,删除操作也就更复杂,以下是对链表的实现代码:
package datastructure;
public class Listnode {
private int data;
private Listnode next;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Listnode getNext() {
return next;
}
public void setNext(Listnode next) {
this.next = next;
}
int ListLength(Listnode headnode) { //链表的长度需要从头遍历到尾,时间复杂度为O(n)
int length=0;
Listnode currentnode = headnode;
while(currentnode != null) {
length++;
currentnode=currentnode.getNext();
}
return length;
}
Listnode InsertInLinkedList(Listnode headnode, Listnode nodeToInsert, int position) {
if(headnode == null) {
return nodeToInsert;
}
int size = ListLength(headnode);
if(position > size+1 || position < 1) {
System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
return headnode;
}
if(position == 1) {
nodeToInsert.setNext(headnode);
return nodeToInsert;
}else {
//在链表中间或者尾部插入
Listnode previousnode = headnode;
int count=1;
while(count < position -1) {
previousnode = previousnode.getNext();
count++;
}
Listnode currentNode = previousnode.getNext();
nodeToInsert.setNext(currentNode);
previousnode.setNext(nodeToInsert);
}
return headnode;
}
Listnode DeleteNodeFromLinkedList(Listnode headnode, int position) {
int size = ListLength(headnode);
if(position > size+1 || position < 1) {
System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
return headnode;
}
if(position == 1) {
Listnode currentNode = headnode.getNext();
headnode = null;
return currentNode;
}else {
Listnode previousNode = headnode;
int count =1;
while(count < position) {
previousNode = previousNode.getNext();
count++;
}
Listnode currentnode = previousNode.getNext();
previousNode.setNext(currentnode.getNext());
currentnode = null;
}
return headnode;
}
public static void main(String[] args) {
Listnode head = new Listnode();
head.setData(9);
System.out.println();
}
}