class Node{
//节点的值
int val;
//下一个节点
Node next;
public Node(int val){ this.val = val; }
}
Node initialLinkedList(int[] vals){
Node head = null, cur = null;
for(int i = 0; i < vals.length, i++){
Node newNode = new Node(vals[i]);
if(i == 0){
head = newNode;
cur = newNode;
}else{
//总结:.next用来构建逻辑关系,直接赋值才做到了移动
cur.next = newNode;
//这里千万不要忘了把newNode赋值给cur,不然一直就只是在更新头结点后面一个节点。
cur = newNode;
}
}
return head;
}
int getLength(Node head){
int length = 0;
Node node = head;
while(node != null){
length++;
node = node.next;
}
return length;
}
关键:newNode.next = head; head = newNode
,注意不要写反为 newNode = head
,因为最后返回的是head
关键:找到要插入位置的前一个节点,然后:newNode.next = cur.next; cur.next = newNode;
这两行代码的先后顺序是不能变的,因为一旦先将新节点赋值给cur.next
,那么原来的cur.next
就找不到了,再写newNode.next = cur.next;
就等同于将新节点的next
又指向了自己
关键:找到末尾节点后将新节点赋值给末尾节点的next就ok
Node insertNode(Node head, Node nodeInsert, int position){
//首先判空
if(head == null){
return null;
}
//判断是否越界
int size = getLength(head);
if(positon > size + 1 || position < 1){
System.out.println("插入越界");
return head;
}
//在链表头插入
if(position == 1){
nodeInsert.next = head;
head = nodeInsert;
return head;
}
//在中间插入
int count = 1;
Node cur = head;
while(count < position - 1){
cur = cur.next;
count++;
}
nodeInsert.next = cur.next;
cur.next = nodeInsert;
return head;
}
关键:直接return head.next;
关键: 找到要删除的前一个节点,然后cur.next = cur.next.next;
关键: 找到末尾的前一个节点,和删除中间节点一样的操作。
Node deleteNode(Node head, int position){
//首先判空
if(head == null){
return null;
}
//判断是否越界
int size = getLength(head);
// 为什么这里position只能允许到size而不能允许到size+1?
// 答:因为删除用的逻辑是找到要删除的前一个节点,就算要删除末尾也不可能要用到size+1
if(position > size || position < 1){
System.out.println("删除越界");
return head;
}
//删除头结点
if(positon == 1){
return head.next;
}else{
//删除中间节点(包括尾部节点)
Node cur = head;
for (int count = 1; count < position - 1; count++) {
cur = cur.next;
}
cur.next = cur.next.next;
}
return head;
}