題目描述
輸入一個單向鏈表和一個節點的值,從單向鏈表中刪除等於該值的節點,刪除後若是鏈表中無節點則返回空指針。
鏈表結點定義以下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
詳細描述:
本題爲考察鏈表的插入和刪除知識。
鏈表的值不能重複
構造過程,例如
1 -> 2
3 -> 2
5 -> 1
4 -> 5
7 -> 2
最後的鏈表的順序爲 2 7 3 1 5 4
刪除 結點 2
則結果爲 7 3 1 5 4
輸入描述:
1 輸入鏈表結點個數
2 輸入頭結點的值
3 按照格式插入各個結點
4 輸入要刪除的結點的值
輸出描述:
輸出刪除結點後的序列
輸入例子:
5
2
3 2
4 3
5 2
1 4
3
輸出例子:
2 1 5 4
算法實現
import java.util.List;
import java.util.Scanner;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
private static class ListNode {
int key;
ListNode next;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNextLong()) {
int num = scanner.nextInt();
int h = scanner.nextInt();
ListNode head = new ListNode();
head.key = h;
for (int i = 0; i < num - 1; i++) {
int newVal = scanner.nextInt();
int afterVal = scanner.nextInt();
addNode(newVal, afterVal, head);
}
int del = scanner.nextInt();
head = delete(del, head);
System.out.println(getString(head));
}
scanner.close();
}
private static String getString(ListNode head) {
StringBuilder builder = new StringBuilder();
while (head!= null) {
builder.append(head.key).append(' ');
head = head.next;
}
// return builder.substring(0, builder.length() - 1);
return builder.toString();
}
private static void addNode(int newVal, int afterVal, ListNode head) {
ListNode n = head;
while (n != null) {
if (n.key == afterVal) {
ListNode node = new ListNode();
node.key = newVal;
node.next = n.next;
n.next = node;
break;
}
n = n.next;
}
}
private static ListNode delete(int val, ListNode head) {
if (head.key == val) {
ListNode ret = head.next;
head.next = null;
return ret;
} else {
ListNode prev = head;
while (prev.next != null) {
if (prev.next.key == val) {
prev.next = prev.next.next;
break;
}
prev = prev.next;
}
return head;
}
}
}