-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
83 lines (66 loc) · 2.43 KB
/
LinkedList.java
File metadata and controls
83 lines (66 loc) · 2.43 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
import java.util.Map;
import java.util.HashMap;
import java.util.*;
public class LinkedList {
//Node object to make up the linked list
private class Node{
Node next;
int data;
public Node(int data){
this.data = data;
}
}
private Node head;
//Time complexity: O(n) - appending to the end of the linked list requires traversal of n items to reach the last null node
public void append(int data){
Node current = head;
//if the head is null, create the first node
if(head == null){
head = new Node(data);
}
else{
//traverse all elements to shift the pointer to the end
while(current.next != null){
current = current.next;
}
//create the new node
current.next = new Node(data);
}
}
//Time complexity: O(1) - creating a new node and shifting a pointer does not create a lot of overhead
public void prepend(int data){
//create the new head
Node tempNewHead = new Node(data);
tempNewHead.next = head; //the current head becomes the new head's next node
head = tempNewHead; //re-route the head to be the first node
}
//Time complexity: Best: O(1) - delete the head being the first data node. Worst: O(n) - iterating through all the elements to find the data node for deletion
public void delete(int data){
Node current = head;
//no nodes in the linked list
if(current == null) return;
//if the data is at the head, just make the next node the head pointer effectively removing visibility to the head (data is still stored in memory)
if(current.data == data){
current = current.next;
} else{
//iterate through elements until data is found
while(current.next != null ){
if(current.next.data == data){
//re-assign the next pointer
current.next = current.next.next;
return; //stop after the first data containing node is found
}
current = current.next;
}
}
}
// public void print(){
// Node current = head;
// System.out.println(current.data);
//
// while(current.next != null){
// current = current.next;
// System.out.println(current.data);
// }
// }
}