Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class ListNode {
- public int value;
- public ListNode next;
- public ListNode(int value){
- this.value = value;
- }
- }
- class LinkedList {
- public int length = 0;
- public ListNode head;
- public ListNode tail;
- // Time Complexity: O(N)
- // Auxiliary Space Complexity: O()
- public void append(int value){
- //add node to the end
- insert(value, length);
- }
- // Time Complexity: O(N)
- // Auxiliary Space Complexity: O(1)
- public void insert(int value, int index){
- //check to see if index for insertion is out of bounds of the LinkedList
- if(index > length || index < 0){
- return;
- }
- ListNode newNode = new ListNode(value);
- //if no nodes exist, new node is head AND tail
- if(length == 0){
- head = newNode;
- tail = newNode;
- }else if(index == 0){
- //set new node to pt to curr head next
- //set head to pt to new node
- newNode.next = head;
- head = newNode;
- }else if(index == length){
- tail.next = newNode;
- tail = newNode;
- }else{
- //if inserting somewhere in the middle->
- //make iterator node variable and set to head of LinkedList
- ListNode previousNode = head;
- for(int i = 0; i< index-1; i++){
- previousNode = previousNode.next;
- }
- //once node previous to index, insert newNode
- newNode.next = previousNode.next;
- previousNode.next = newNode;
- }
- //increase length to acct for inserted node
- length++;
- }
- // Time Complexity: O(N)
- // Auxiliary Space Complexity: O(1)
- public void delete(int index){
- //out of bounds? return
- if(index < 0 || index >= length){
- return;
- }
- //if there is only 1 item in LinkedList
- if(length == 1){
- head = null;
- tail = null;
- }else if(index == 0){
- head = head.next;
- }else {
- //create iterator
- ListNode previousNode = head;
- for(int i = 0 ; i <index-1; i++){
- previousNode = previousNode.next;
- }
- previousNode.next = previousNode.next.next;
- if(index == length -1){
- tail = previousNode;
- }
- }
- length--;
- }
- // Time Complexity: O(N)
- // Auxiliary Space Complexity: O(1)
- public boolean contains(int value){
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement