0% found this document useful (0 votes)
9 views32 pages

Lecture04 Arrays Singly Linked Lists

The document discusses different list data structures including arrays, singly linked lists, circularly linked lists and doubly linked lists. It provides examples of implementing a scoreboard using arrays and describes operations like insertion, removal and sorting of elements in arrays. It also explains the concept of singly linked lists and provides code to implement basic linked list operations.

Uploaded by

zaina muhtaseb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views32 pages

Lecture04 Arrays Singly Linked Lists

The document discusses different list data structures including arrays, singly linked lists, circularly linked lists and doubly linked lists. It provides examples of implementing a scoreboard using arrays and describes operations like insertion, removal and sorting of elements in arrays. It also explains the concept of singly linked lists and provides code to implement basic linked list operations.

Uploaded by

zaina muhtaseb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

CSE214 Data Structures

Arrays and Singly Linked Lists

YoungMin Kwon
Lists
 List
 A linear sequence of elements

 Implementations
 Arrays
 Singly linked lists
 Circularly linked lists
 Doubly linked lists
Arrays
 Example 1
 Storing game entries for a video
game in an array

 Information to store
 Name of the player
 Score of the game

 GameEntry class for the entries


Scoreboard
 A class to store the high scores
 Use a fixed length array of GameEntry
 The entries in the list are sorted from highest
score to lowest one
Adding an Entry
 Adding a new entry to a Scoreboard
 If the board is not full, any new entry will be added

 If the board is full, a new entry will be added only


when it is strictly better than the other scores
 Better than the last entry

 To add a new entry


 To make room, shift downward the entries that have lower
score than the new one
 Add the new entry to the empty space
 Make room for a
new reference

 Add a reference to
Kim
Removing an Entry
 Removing an entry at index i from a
Scoreboard

 When an entry is removed, any lower scores


should be shifted upward to fill the empty space

 If i is outside of the current entries throw an


IndexOutOfBoundsException

 Return the entry that was removed


Sorting an Array
 The insertion‐sort algorithm
 Works similarly as the Scoreboard example
 Given an array of length n
 Consider only the first k elements of the array at a
time while changing k from 1 to n‐1
 Insert the kth element to the first k sorted
elements
Insertion‐sort
Insertion‐sort
Insertion‐sort (using swap)
//swap data[i] and data[j]
public static void swap(char[] data, int i, int j) {
char tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
//insertion sort (using swap)
public static void insertionSort(char[] data) {
int n = data.length;
for(int k = 1; k < n; k++) {
for(int j = k; j > 0; j‐‐) {
if(data[j‐1] > data[j]) {
swap(data, j‐1, j);
}
}
}
}
public static void main(String[] args) {
char[] data = new char[] {'s', 'a', 'm', 'p', 'l', 'e'};
insertionSort(data);
for(char c : data)
System.out.print (c + " ");
}
Insertion‐sort

 Insertion sort demo


 https://www.youtube.com/watch?v=ROalU379l3U
Singly Linked Lists
 Drawbacks of using arrays
 The capacity of an array must be fixed when it is
created
 In many applications, we cannot predict the required
capacity
 Allocate for the possible maximum  waste of memory

 Insertion and deletion are time consuming


 Shifting many elements
Singly Linked Lists
 Linked List
 A collection of nodes that form a linear sequence

 Node
 Has a reference to its element object
 Has a reference to the next node
Singly Linked Lists
 Linear structure

 Head: points to the first node


 Tail: points to the last node
 Tail node has null in its next reference variable
 Tail node can be found by following the nodes from the head
 Count: the number of elements in the list
 Count can be computed while traversing along the nodes
Inserting an Element
 Inserting a node at the head
 Create a new node with a reference to the element
 Set its next link to reference the node where the
current head is referencing
 Make the head reference the new node
Inserting an Element
Inserting an Element
 Inserting a node at the tail
 Create a new node with a reference to the element
 Set its next link to null
 Make the tail node’s next reference the new node
 Make the tail reference the new node
Inserting an Element
Removing an Element
 Removing a node from the head
 Set the head to the head’s next link
Removing an Element

No one is referencing
this node
⇒it will be garbage
collected
Removing an Element
 Removing a node from the tail
 Unfortunately, it is not easy to remove a node
from the tail
 Need to find the node before the tail
 Need to scan from the head to the node before
the tail

 This task can be easily achieved using doubly


linked lists
Implementing SinglyLinkedList
public class SinglyLinkedList<E> {
//Node of the list
private static class Node<E> {
private E e; //element
private Node<E> next; //next node

public Node(E e, Node<E> n) { this.e = e; this.next = n; }


public E getElement() { return e; }
public Node<E> getNext() { return next; }
public void setNext(Node<E> n) { next = n; }
}

private Node<E> head, tail;


private int size;

public SinglyLinkedList() {}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public E first() {
return isEmpty() ? null : head.getElement();
}

public E last() {
return isEmpty() ? null : tail.getElement();
}

public void addFirst(E e) {


head = new Node<>(e, head);
if(isEmpty()) //special handling for empty case
tail = head;
size++;
}

public void addLast(E e) {


if(isEmpty()) //special handling for empty case
addFirst(e);
else {
tail.setNext(new Node<>(e, null));
tail = tail.getNext();
size++;
}
}
public E removeFirst() {
if(isEmpty())
return null;

//return value
E ret = head.getElement();

//make head point to the next node


head = head.getNext();
size‐‐;

//if empty, make tail null


if(size == 0)
tail = null;

return ret;
}

public E removeLast() {
//TODO: implement this method
}
private static void onFalseThrow(boolean b) {
if(!b)
throw new RuntimeException("Error: unexpected");
}

public static void main(String[] args) {


SinglyLinkedList<Integer> list =
new SinglyLinkedList<>();

list.addLast(2);
list.addLast(3);
list.addLast(4);
list.addFirst(1);

onFalseThrow(list.removeLast() == 4);
onFalseThrow(list.removeLast() == 3);
onFalseThrow(list.removeFirst() == 1);
onFalseThrow(list.removeLast() == 2);
System.out.println("Success!");
}
}

You might also like