题解 | #【模板】链表#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
思路:
为了避免要经常判断 链表是否为空 这一麻烦事,所以在进行 初始化 的时候,我们定义一个 头指针。注意区分 头指针 和 头节点 的区别。有了 头指针 之后,就是正常的链表操作了(插入、删除)。不过要小心的是,打印 链表的时候,不要 将 头指针 给打印了。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.valueOf(scan.nextLine().trim());
for (int i = 0; i < n; i++) {
String[] operator = scan.nextLine().split(" ");
if ("insert".equals(operator[0])) {
insert(Integer.valueOf(operator[1]), Integer.valueOf(operator[2]));
} else {
delete(Integer.valueOf(operator[1]));
}
}
ListNode node = head;
if (null == node.next) {
System.out.println("NULL");
return;
}
while (null != node.next) {
System.out.print(node.next.val + " ");
node = node.next;
}
}
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public static ListNode head = new ListNode(-1);
public static void insert(int x, int y) {
ListNode newNode = new ListNode(y);
ListNode node = head;
int sign = 0;
while (null != node.next) {
if (node.next.val == x) {
newNode.next = node.next;
node.next = newNode;
sign = 1;
break;
}
node = node.next;
}
if (sign == 0) {
node.next = newNode;
}
}
public static void delete(int x) {
ListNode node = head;
while (null != node.next) {
if (node.next.val == x) {
node.next = node.next.next;
break;
}
node = node.next;
}
}
}