Skip to content

Commit ce5c1d7

Browse files
Create Double Linked List.md
1 parent 214c2b7 commit ce5c1d7

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Summary
2+
3+
4+
## Double Linked List (DLL)
5+
#### Node class variables:
6+
```java
7+
private E element; // reference to the element stored at this node
8+
private Node<E> prev; // reference to the previous node in the list
9+
private Node<E> next; // reference to the subsequent node in the list
10+
```
11+
#### DLL class variables:
12+
```java
13+
private Node<E> header; // header sentinel
14+
private Node<E> trailer; // trailer sentinel
15+
private int size = 0; // number of elements in the list
16+
```
17+
### methods:
18+
- **size( ):** Returns the number of elements in the list.
19+
- **isEmpty( ):** Returns true if the list is empty, and false otherwise.
20+
- **first( ):** Returns (but does not remove) the first element in the list.
21+
- **last( ):** Returns (but does not remove) the last element in the list.
22+
- **addFirst(e):** Adds a new element to the front of the list.
23+
- **addLast(e):** Adds a new element to the end of the list.
24+
- **removeFirst( ):** Removes and returns the first element of the list.
25+
- **removeLast( ):** Removes and returns the last element of the list.
26+
27+
| Operations | Access | Search | Insertion | Deletion |
28+
|----------------------------|--------|--------|-----------|----------|
29+
| Best case time complexity | O(1) | O(1) | O(1) | O(1) |
30+
| Worst Case time complexity | O(n) | O(n) | O(1) | O(1) |
31+
| Average time complexity | O(n) | O(n) | O(1) | O(1) |
32+
33+
### special method:
34+
```java
35+
/** Removes and returns the last element of the list. */
36+
public E removeLast( ) {
37+
if (isEmpty( )) return null; // nothing to remove
38+
return remove(trailer.getPrev( )); // last element is before trailer
39+
}
40+
41+
/** Removes the given node from the list and returns its element. */
42+
private E remove(Node<E> node) {
43+
Node<E> predecessor = node.getPrev( );
44+
Node<E> successor = node.getNext( );
45+
predecessor.setNext(successor);
46+
successor.setPrev(predecessor);
47+
size−−;
48+
return node.getElement( );
49+
}
50+
```

0 commit comments

Comments
 (0)