题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
java
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); while(scanner.hasNext()){ //示例中的第1个数,6 int num =scanner.nextInt(); //示例中的第2个数,2,头结点 Node head = new Node(scanner.nextInt()); num--; //构造题目给出的链表。 while(num>0){ //比如输入 1 2 , 2->1 表示在2这个节点后面插上1这个节点。 //所以当前节点是1, 前面一个节点是2 int cur = scanner.nextInt(); int pre = scanner.nextInt(); insert(head,pre,cur); num--; } //链表构造完成后,删除输入的指定的节点。 int deleteVal = scanner.nextInt(); //删除头结点2 if(head.val == deleteVal){ head = head.next; }else{ delete(head,deleteVal); } Node test = head; //打印输出 while(test != null){ System.out.print(test.val + " "); test = test.next; } //千万别忘了换行!!!!!! System.out.println(); } } //插入Node public static void insert(Node head,int preVal,int newVal){ //要被插入的节点。 Node newNode = new Node(newVal); Node cur = head; Node temp; while(cur != null){ if(cur.val == preVal){ temp = cur.next; cur.next = newNode; newNode.next = temp; return; } cur = cur.next; } } public static void delete(Node head,int delVal){ Node cur = head; Node temp; while(cur.next != null){ if(cur.next.val == delVal){ cur.next = cur.next.next; return; } cur = cur.next; } } } //节点构造 class Node{ int val; Node next; Node(int val){ this.val = val; } }