import static java.lang.reflect.Array.getLength;
public class MyBasicLink {
//主函数
public static void main(String[] args) {
int[] a={1,2,3,4,5,6};
Node head = initLinkList(a);
System.out.println("head:"+head);
System.out.println("value of head:"+head.val);
int listLength = getListLength(head);
System.out.println("length of linklist:"+listLength);
Node node=new Node(9);
Node head2 = insertNode(head, node, 7);
System.out.println("updated head:"+head2);
System.out.println("head2:"+head2);
System.out.println("value of head2:"+head2.val);
System.out.println("value of last node:"+node.val);
int listLength2 = getListLength(head2);
System.out.println("length of linklist2:"+listLength2);
Node head3 = deleteNode(head2, 7);
int listLength3 = getListLength(head3);
System.out.println("deleted length of linklist:"+listLength3);
}
//定义结点 要是静态的
static class Node{
int val;
Node next;
Node(int data){
this.val = data;
}
}
//初始化链表 以后不再调用 增加用插入链表
public static Node initLinkList(int[] array){
Node head = null,cur = null;
for(int i = 0;i < array.length;i++){
Node newNode = new Node(array[i]);
newNode.next=null;
if(i==0){
head=newNode;
cur=newNode;
}else{
cur.next=newNode;
cur=newNode;
}
}
return head;
}
//获取链表长度
public static int getListLength(Node head){
int length=0;
Node node=head;
while(node!=null){
length++;
node=node.next;
}
return length;
}
//插入结点到链表
public static Node insertNode(Node head,Node nodeInsert,int position){
if(head==null){
return nodeInsert;//这里没有头结点,那nodeInsert就相当于头节点
}
//已经存放的元素个数
int size=getListLength(head);
if(position>size+1||position<1){
System.out.println("位置参数越界");
return head;
}
//表头插入
if(position==1){
nodeInsert.next=head;
head=nodeInsert;
return head;
}
//中间插入或者表尾插入
Node pNode=head;
int count=1;
while(count<position-1){
pNode=pNode.next;
count++;
}
nodeInsert.next=pNode.next;
pNode.next=nodeInsert;
return head;
}
//删除结点
public static Node deleteNode(Node head,int position){
if(head==null){
return null;
}
int size=getListLength(head);
if(position>size||position<1){
System.out.println("输入的参数有误");
return head;
}
if(position==1){//删除头结点
return head.next;
}else { //删除中间结点或者尾部结点
Node cur=head;
int count=1;
while(count<position-1){
cur=cur.next;
count++;
}
cur.next=cur.next.next;
}
return head;
}
}
青铜挑战—小白也能学会的链表(java实现)
最新推荐文章于 2024-10-06 20:16:20 发布