1. 创建一个链表类,方便对链表进行操作,创建三个构造方法,无参的主要创建头结点
package com.linked;
public class Node {
public Integer data;
public Node next;
public Node() {
}
public Node(Integer data) {
this.data = data;
}
public Node(Integer data, Node next) {
this.data = data;
this.next = next;
}
}
2.链表的增删改查操作
package com.linked;
public class LinkClass {
private static Node head = new Node();
/**
* 给数组增加数据
* @param data
*/
public static void addLink(Node head, int data){
// 定位头结点方便操作
Node temp = head;
// 构造新增节点的数值
Node newNode = new Node(data);
while (temp.next != null){
temp = temp.next;
}
temp.next = newNode;
}
/**
* 遍历整个链表
* @param head
*/
public static void adverseLinked(Node head){
Node temp = head.next;
while(temp != null){
if(temp.data != null){
System.out.println("data的数据为:" + temp.data);
}
temp = temp.next;
}
}
/**
* 增加节点数据
* @param head
* @param index
* @param data
*/
public static void insertLinked(Node head, int index, int data){
Node temp = head.next;
Node newNode = new Node(data);
int currentPos = 0;
if(index < 1 || index > linkLength(head) + 1){
System.out.println("输出位置不正确,无法插入");
return;
}
while(temp != null){
if(currentPos == (index - 1)){
newNode.next = temp.next;
temp.next = newNode;
}
temp = temp.next;
currentPos ++;
}
}
public static void deleteLinked(Node head, int index){
Node temp = head.next;
int currpos = 0;
if(index < 1 || index > linkLength(head) + 1){
System.out.println("节点无效");
}
while(temp != null){
if(currpos == (index - 1)){
Node deNode = temp.next;
temp.next = deNode.next;
deNode = null;
}
currpos ++;
temp = temp.next;
}
}
public static int linkLength(Node head){
int length = 0;
Node temp = head;
while(temp.next != null){
length ++;
temp = temp.next;
}
return length;
}
public static void main(String[] args) {
addLink(head,11);
addLink(head,12);
addLink(head,13);
addLink(head,14);
insertLinked(head,2,20);
deleteLinked(head,3);
adverseLinked(head);
}
}