-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.java
55 lines (47 loc) · 1.14 KB
/
LinkedList.java
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
public class LinkedList<Item>
{
private class Node
{
public Item item;
public Node next;
}
public Node first;
public void add(Item item)
{
Node node = new Node();
node.item = item;
node.next = first;
first = node;
}
public void delete(int k)
{
if (k == 0){ first = first.next; }
else {
int n = 0;
for (Node x = first; x != null; x = x.next)
{
if (n == k - 1) { x.next = x.next.next; }
n++;
}
}
}
public void printList()
{
for (Node x = first; x != null; x = x.next)
{ StdOut.print(x.item + " "); }
StdOut.println();
}
public static void main(String[] args)
{
LinkedList l = new LinkedList();
while(!StdIn.isEmpty())
{
l.add(StdIn.readString());
}
StdOut.println("Here's the list before deleting K:");
l.printList();
l.delete(Integer.parseInt(args[0]));
StdOut.println("Here's the list after deleting K:");
l.printList();
}
}