1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| import java.util.*;
class ListNode{ int val; ListNode next; ListNode(){} ListNode(int val){ this.val = val; } }
class LinkedList{ ListNode head; int size; LinkedList(){ this.size = 0; this.head = new ListNode(0); } public boolean insert(int index, int val){ if (index < 1 || index > size + 1){ return false; } this.size++; ListNode newNode = new ListNode(val); ListNode pre = head; for(int i = 0; i < index - 1; i++){ pre = pre.next; } newNode.next = pre.next; pre.next = newNode; return true; } public boolean delete(int index){ if (index < 1 || index > size){ return false; } this.size--; ListNode pre = head; for(int i = 0; i < index - 1; i++){ pre = pre.next; } pre.next = pre.next.next; return true; } public void printList(){ ListNode cur = head.next; while (cur != null){ System.out.print(cur.val + " "); cur = cur.next; } System.out.println(); } }
class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNextInt()){ int k = sc.nextInt(); LinkedList result = new LinkedList(); while (k-- > 0){ result.insert(result.size + 1, sc.nextInt()); } int S = sc.nextInt(); while (S-- > 0){ int n = sc.nextInt(); int x = sc.nextInt(); if (result.insert(n,x)){ result.printList(); } else { System.out.println("Insertion position is invalid."); } } int L = sc.nextInt(); while (L-- > 0){ int m = sc.nextInt(); if (result.delete(m)){ result.printList(); } else { System.out.println("Deletion position is invalid."); } } } sc.close(); } }
|