从零开始,0为第一个元素
每一个结点就是一个对象
package listNode;
public class ListNode {
public int value; //节点当中的数组区域
public ListNode next; //记录下一个节点的地址 ---->java是强类型的语言,定义什么类型就要开辟什么样的内存空间
//因为对象就是ListNode,而所存在的next就是地址,所以将要求ListNode的类型
//相当于记录的是对象的地址
public ListNode(int value){
this.value=value;
}
@Override
public String toString() {
return "ListNode{" +
"value=" + value +
", next=" + next +
'}';
}
}
解析:我们需要统计,需要第几个位置插入,然后找到该位置的前驱结点,因为只有直到前驱结点才能插入进去
再插入之前需要判单index位置合不合法,如果小于0或者大于链表的长度则不能插入
代码实现
public void deleteNodeIndex(int index) {
if (index < 0 || index > linkLength()) {
System.out.println("你输入的数据不合法...");
return;
}
//0为第一个元素
if (index == 0) {
head = head.next;
return;
}
ListNode indexNode = head;
ListNode preNode = null;
int position = 0;
while (indexNode != null) {
if (position == index) {
preNode.next = indexNode.next;
return;
}
preNode = indexNode;
indexNode = indexNode.next;
position++;
}
}
解析:这里我需要使用快慢指针的思想,快指针走两步,慢指针走一步。当快指针走到空,那么此时慢指针的位置就是中间结点
代码实现
public ListNode midValue() {
if (head == null) {
System.out.println("链表为空链表");
return null;
}
ListNode res = null;
ListNode fastNode = head;
ListNode slowNode = head;
while (fastNode != null && fastNode.next != null) {
fastNode = fastNode.next.next;
slowNode = slowNode.next;
}
res = slowNode;
return res;
}
解析:
代码实现
public ListNode fanzhuan() {
ListNode next = null;
ListNode pre = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
head = pre;
return head;
}