import java.util.List;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
MyLinkedList list = new MyLinkedList();
int count = 0;
if (in.hasNextLine())
count = Integer.parseInt(in.nextLine());
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine() && (count--) > 0) {
String[] arr = in.nextLine().split(" ");
String ListOperation = arr[0];
if (ListOperation.equals("insert")) {
list.insertNode(Integer.parseInt(arr[1]), Integer.parseInt(arr[2]));
} else if (ListOperation.equals("delete")) {
list.deleteNode(Integer.parseInt(arr[1]));
} else {
System.out.println("非法输入");
}
}
System.out.println(list);
}
}
class MyLinkedList {
ListNode head;
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
if (head == null)
return "NULL";
else {
ListNode node = head;
while (node != null) {
stringBuilder.append(node.val + " ");
node = node.next;
}
}
return stringBuilder.toString();
}
public void insertNode(int x, int y) {
// 首次插入(长度为0时)
if (head == null) {
head = new ListNode(y);
return;
}
// 后续插入
ListNode l = head, ll = l;
// 长度为1时或head刚好匹配上
if (head.val == x) {
ll = head;
head = new ListNode(y);
head.next = ll;
return;
}
// 长度>=2时且不考虑head刚好匹配上的情况
while (l.next != null) {
ll = l;
l = l.next;
if (l.val == x) {
ll.next = new ListNode(y);
ll.next.next = l;
return;
}
}
l.next = new ListNode(y);//末尾插入
}
public void deleteNode(int val) {
// write code here
ListNode l = head, mid;
if (head == null)
return;
if (head.val == val)
head = head.next;
for (mid = l.next; mid != null; ) {
if (mid.val == val) {
l.next = mid.next;
mid.next = null;
break;
} else {
l = l.next;
mid = mid.next;
}
}
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
这题是真的坑啊,很多细节和情况需要考虑。

京公网安备 11010502036488号