forked from mattlevan/Simple_Card_Game
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleLinkedList.java
More file actions
112 lines (89 loc) · 2.23 KB
/
SingleLinkedList.java
File metadata and controls
112 lines (89 loc) · 2.23 KB
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
105
106
107
108
109
110
111
112
/*
* Matt Levan
* CSC 331, Dr. Amlan Chatterjee
* Data Structures
*
* Implement a singly linked list
*
* Must include methods:
* addFirst, addAfter add, removeAfter, removeFirst, printList, getNode
*
* Due in full by 10/15/2015
*
*/
class Node {
// Attributes
Object data;
Node next;
// Constructors
public Node(Object data) {
this.data = data;
this.next = null;
}
}
public class SingleLinkedList {
// Attributes
private Node head = new Node(-1);
public int size = 0; // Size of linked list in number of Node
// Methods
// Adds by default to the end
public void add(Object item) {
addAfter(item, getNode(size));
}
public void add(Object item, int index) {
if (index < 0 || index > size) {
return;
}
if (index == 0) {
addFirst(item);
}
else {
addAfter(item, getNode(index - 1));
}
}
public void addFirst(Object item) {
Node first = new Node(item); // Create new first Node
first.next = head.next;
head.next = first;
size++;
}
public void addAfter(Object item, Node target) {
Node after = new Node(item);
after.next = target.next;
target.next = after;
size++;
}
public Object removeFirst() {
if (size > 0) {
Node first = head.next;
head.next = first.next;
size--;
return first.data;
}
return null;
}
public Object removeAfter(Node target) {
if (target.next != null) {
Node after = target.next;
target.next = after.next;
size--;
return after.data;
}
return null;
}
public Node getNode(int index) {
Node node = head;
for (int i = 0; i < index && node != null; i++) {
node = node.next;
}
return node;
}
// Custom printList for cards
public void printList(Node head) {
Node temp = head.next; // Start printing at node AFTER head
while (temp != null) {
System.out.print(temp.data.toString() + " ");
temp = temp.next;
}
}
}