数据结构
public class Node {
public int val;
public Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
", next=" + next +
'}';
}
}
实现代码
public class BasicLinkList {
public static void main(String[] args) {
Node node = new Node(1);
insertNode(node, new Node(2), 2);
node = insertNode(node, new Node(3), 1);
node = insertNode(node, new Node(666), 1);
System.out.println(getLength(node));
System.out.println(node);
Node deleteNode = deleteNode(node, 2);
System.out.println(getLength(deleteNode));
System.out.println(deleteNode);
}
//获取链表长度
public static int getLength(Node head) {
Node cur = head;
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
//插入节点
public static Node insertNode(Node head, Node newNode, int position) {
int size = getLength(head);
//判空
if (head == null) {
System.out.println("链表为空");
return head;
}
//判断插入位置是否合理
if (position < 1 || position > size + 1) {
System.out.println("参数越界");
return head;
}
//表头插入
if (position == 1) {
newNode.next = head;
head = newNode;
return head;
}
//表中间或末位插入
Node cur = head;
int count = 1;//直接跳过表头,这样下面的循环条件就不要判断null了
//也不能说跳过表头,count的值应该和cur一一对应,cur指向头节点,所以count应该从1开始
// while (count < position - 1 && cur.next != null) {
while (count < position - 1) {
cur = cur.next;
count++;
}
newNode.next = cur.next;
cur.next = newNode;
return head;
}
//删除节点
public static Node deleteNode(Node head, int position) {
int size = getLength(head);
//判断是否空节点
if (head == null) {
System.out.println("链表为空");
return head;
}
//判断下标是否越界
if (position < 1 || position > size) {
System.out.println("下标越界");
return head;
}
//删除头节点
if (position == 1) {
head = head.next;
return head;
}
//删除表中或者末位节点
int count = 1;
Node cur = head;
while (count < position - 1) {
cur = cur.next;
count++;
}
cur.next = cur.next.next;
return head;
}
/**
* 输出链表
*
* @param head 头节点
*/
public static String toString(Node head) {
Node current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.val).append("\t");
current = current.next;
}
return sb.toString();
}
}
一些遇到的坑
//表中间或末位插入
Node cur = head;
int count = 1;//直接跳过表头,这样下面的循环条件就不要判断null了
//也不能说跳过表头,count的值应该和cur一一对应,cur指向头节点,所以count应该从1开始
// while (count < position - 1 && cur.next != null) {
while (count < position - 1) {
cur = cur.next;
count++;
}
这里一开始count从0开始,没有跳过表头,会导致空指针的错误