增删改查写腻了嘛 跟我一起手写链表的实现吧
仅为学习用,所以这里数据域只存int类型的数据了
代码语言:javascript复制public class LinkList {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
Node head = initLinkedList(a);
System.out.println("初始化成功");
System.out.println("获取长度:" getLength(head));
System.out.println("转为字符串输出:" toString(head));
head = insertNode(head,new Node(0),1);
System.out.println("头插:" toString(head));
head = insertNode(head,new Node(7),7);
System.out.println("尾插:" toString(head));
head = deleteNode(head,1);
System.out.println("头删:" toString(head));
head = deleteNode(head,6);
System.out.println("尾删:" toString(head));
}
/**
* 插入节点
* @param head 头结点
* @param insertNode 待插入结点
* @param position 插入位置
* @return 插入后的链表头结点
*/
public static Node insertNode(Node head,Node insertNode,int position){
//判空
if(head==null){
return insertNode;
}
//判断是否越界
int size = getLength(head);
if(position>size 1||position<1){
System.out.println("越界异常");
return head;
}
//头插
if(position==1){
insertNode.next = head;
head = insertNode;
return head;
}
//中间及尾插
Node midNode = head;
int count = 0;
while (count < position-1){
midNode = midNode.next;
count ;
}
insertNode.next = midNode.next;
midNode.next = insertNode;
return head;
}
/**
* 删除结点
* @param head 头结点
* @param position 删除的位置
* @return 输出的链表
*/
public static Node deleteNode(Node head,int position){
//判空
if(head==null){
System.out.println("链表为空,无法删除");
return null;
}
//判断参数是否越界
int size = getLength(head);
if(position>size||position<=0){
System.out.println("位置参数输入有误");
return head;
}
if(position==1){
return head.next;
}
Node midNode = head;
int count = 1;
while (count<position){
count ;
midNode = midNode.next;
}
midNode.next = midNode.next.next;
return head;
}
/**
* 输出链表
* @param head 头结点
* @return 输出的链表
*/
public static String toString(Node head){
Node node = head;
StringBuilder str = new StringBuilder();
while (node!=null){
str.append(node.val).append(" ");
node = node.next;
}
return str.toString();
}
/**
* 获取链表长度
* @param head 头结点
* @return 链表长度
*/
public static int getLength(Node head){
int length = 0;
Node node = head;
while (node!=null){
length ;
node = node.next;
}
return length;
}
/**
* 链表初始化
* @param array
* @return
*/
public static Node initLinkedList(int[] array){
Node head = null,cur = null;
for (int i = 0; i < array.length; i ) {
Node newNode = new Node(array[i]);
if(i==0){
head = newNode;
cur = head;
}else {
cur.next = newNode;
cur = newNode;
}
}
return head;
}
static class Node{
public int val;
public Node next;
Node(int x) {
val = x;
next = null;
}
}
}