Skip to content

Commit c65e562

Browse files
committed
Added Queues, Priority Queues and Linked Lists
1 parent 67d3bf5 commit c65e562

File tree

2 files changed

+71
-2
lines changed

2 files changed

+71
-2
lines changed

data_structures/LinkedLists.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
3+
* With a linked list you do not need to predetermine it's size as it grows and shrinks as it is edited.
4+
* This is an example of a singly linked list. Elements can only be added/removed at the head/front of the list.
5+
*/
6+
class LinkedList{
7+
private Link head; //Head refers to the front of the list
8+
9+
public LinkedList(){
10+
head = null;
11+
}
12+
13+
public void insertHead(int x){ //Insert an element at the head
14+
Link newLink = new Link(x); //Create a new link with a value attached to it
15+
newLink.next = head; //Set the new link to point to the current head
16+
head = newLink; //Now set the new link to be the head
17+
}
18+
19+
public Link deleteHead(){ //Delete the element at the head
20+
Link temp = head;
21+
head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
22+
return temp;
23+
}
24+
25+
public boolean isEmpty(){ //Returns true if list is empty
26+
return(head == null);
27+
}
28+
29+
public void display(){ //Prints contents of the list
30+
Link current = head;
31+
while(current!=null){
32+
current.displayLink();
33+
current = current.next;
34+
}
35+
System.out.println();
36+
}
37+
}
38+
39+
class Link{
40+
public int value;
41+
public Link next; //This is what the link will point to
42+
43+
public Link(int valuein){
44+
value = valuein;
45+
}
46+
47+
public void displayLink(){
48+
System.out.print(value+" ");
49+
}
50+
}
51+
52+
//Example
53+
public class LinkedLists{
54+
public static void main(String args[]){
55+
LinkedList myList = new LinkedList();
56+
57+
System.out.println(myList.isEmpty()); //Will print true
58+
59+
myList.insertHead(5);
60+
myList.insertHead(7);
61+
myList.insertHead(10);
62+
63+
myList.display(); // 10(head) --> 7 --> 5
64+
65+
myList.deleteHead();
66+
67+
myList.display(); // 7(head) --> 5
68+
}
69+
}

data_structures/PriorityQueues.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ public void insert(int value){ //Inserts an element in it's appropriate place
2222
else{
2323
int j = nItems;
2424
while(j > 0 && queueArray[j-1] > value){
25-
queueArray[j] = queueArray[j-1];
25+
queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
2626
j--;
2727
}
28-
queueArray[j] = value;
28+
queueArray[j] = value; //Once the correct position is found the value is inserted
2929
}
3030
nItems++;
3131
}

0 commit comments

Comments
 (0)