Linked Lists

Lesson 11

Last Week

  • dynamic array (Intlist or Int Container and Polygon or Point Container)

This week

  • Scanner

  • LinkedList exercises

  • Doubly linked list (moves forwards and backwards)

Scanner

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int my_int = scan.nextInt();
        double my_double = scan.nextDouble();
        String my_str = scan.next();

        System.out.println("int:" + my_int);
        System.out.println("double:" + my_double);
        System.out.println("string:" + my_str);

        scan.close();
    }
}

LinkedList

advantages of LinkedList

  • removal of element in O(n) i.e. very fast

  • not contiguous in memory, so can expand

disadvantage of LinkedList

  • not contiguous in memory, so its slower to get each node

Basic implementation

Test Exercise: Add to an ordered Linked List

Solution:

Exercise: Find the middle element (position) of LinkedList

  • DIY: - naïve solution

  • Our solution: Find the middle element (position) of LinkedList. You may only iterate through the linkedlist 1 time i.e. O(n)

Solution

The solution is similar to Floyd's cycle finding algorithm

Traverse linked list using two pointers.

  • Move one pointer by 1

  • Move other pointers by 2

When the fast pointer reaches the end slow pointer will reach the middle of the linked list.

Test Exercise: Cycle in LinkedList

Detect if there is cycle in LinkedList

Detect loop in a linked list - GeeksforGeeks

Hint! you should use the code we use before

I have added a print function to show the loop

Solution

Note: since if the linked list is empty the code will work since in

slow_ptr will equal to null and exit the while before checking fast_ptr.next

But how do we remove the the cycle?

Easy just add 1 line of code

so now

Exercise: Reverse LinkedList - Iteratively- DIY (15 minutes)

Solution

reverse-all-steps

Exercise: Reverse LinkedList - Recursively

solution

Exercise: Partition LinkedList

all even numbers appear before all the odd numbers in the modified linked list

linked-LIst-even-odds

Solution

  1. Pointer should be at last node (iterate to get there)

  2. Move all the odd nodes to the end

    • Consider all odd nodes before the first even node and move them to end.

    • Change the head pointer to point to the first even node.

    • Consider all odd nodes after the first even node and move them to the end.

Doubly LinkedList

linked-LIst-doubly

Advantages over singly linked list

  • can traverse in both forward and backward direction

  • and more, so read up

Disadvantages over singly linked list

  • takes up more space

  • All operations require an extra pointer previous to be maintained. For example, in insertion, we need to modify previous pointers together with next pointers.

Last updated

Was this helpful?