这道题是Shopee社招 O2C岗的面试题,没做出来,当场流下了技术太菜的泪水。
可能当时脑子坏了,一开始就没用头结点,后来想起来要用的时候也懒得用了,看面试官的表情也很无奈,索性跟他说我回去重新想想。
package simple;
public class LinkedList {
static Node head= new Node(-1);
public static void main(String[] args) {
insert(2);
insert(1);
insert(2);
insert(2);
insert(3);
insert(2);
insert(4);
print();
delete(2);
print();
}
static class Node {
int val;
Node next;
public Node(int value) {
val = value;
}
@Override
public String toString() {
return String.valueOf(val);
}
}
public static void insert(int value) {
Node node = new Node(value);
node.next = head.next;
head.next = node;
}
public static void delete(int value) {
Node lastNode = head;
Node curNode = head.next;
if (curNode == null) {
return;
}
while (curNode != null) {
if (curNode.val == value) {
lastNode.next = curNode.next;
} else {
lastNode = curNode;
}
curNode = curNode.next;
}
}
public static void print() {
Node node = head.next;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
}
}
程序输出:
4 2 3 2 2 1 2
4 3 1