Linked Lists, Arrays - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

Linked Lists, Arrays

Description:

Linked Lists, Arrays & Matrices. ECE573: Data Structures and Algorithms ... among the instances and among the individual elements that compose an instance ... – PowerPoint PPT presentation

Number of Views:137
Avg rating:3.0/5.0
Slides: 40
Provided by: venkat3
Category:
Tags: arrays | compose | linked | lists

less

Transcript and Presenter's Notes

Title: Linked Lists, Arrays


1
Linked Lists, Arrays Matrices
  • ECE573 Data Structures and Algorithms
  • Electrical and Computer Engineering Dept.
  • Rutgers University
  • http//www.cs.rutgers.edu/vchinni/dsa/

2
Data Structures
  • Data Objects
  • Boolean false, true
  • Digit 0,1,2,3,4,5,6,7,8,9
  • Letter A,B,Z,a,b,..,z
  • NaturalNumber 0,1,2,
  • Integer 0,1,2,-1,-2,
  • String a, b, ,aa,ab,ac,
  • Data object instances have
  • Interrelations positioning
  • Functions transformation, addition
  • Data Structure
  • data object relationships that exists among the
    instances and among the individual elements that
    compose an instance
  • Relationships are provided by specifying
    functions of interest
  • Representation of data objects should facilitate
    an efficient implementation of the functions

Instance
3
Standard Data Types
  • Frequently used data objects functions are
    already implemented in C, C
  • Integer (int)
  • Real (float)
  • Boolean (bool)
  • Other facilities provided thro class, array, and
    pointer features
  • Enumeration
  • Grouping
  • Ex instance of String using a character array s
  • char sMaxSize

4
Data Structures
  • Linear list
  • Matrices
  • Stacks
  • Queues
  • Dictionaries
  • Priority Queues
  • Graphs

Todays class
5
Linear Lists
  • Instances are of the form e1, e2, en where
  • n is a finite natural number and represents the
    length of the list
  • Elements are viewed as atomic ? their individual
    structure is not relevant
  • List is empty ? n0
  • Relations
  • e1 is first element and en is the last
    (Precedence only relation)

6
Operations
  • Create a list
  • Delete a list
  • Determine if list is empty
  • Determine the length of the list
  • Find the kth element
  • Search for a given element
  • Delete the kth element
  • Insert a new element just after the kth

Create() Destroy() IsEmpty() Length() Find(k,x) Se
arch(x) Delete(k,x) Insert(k,x)
Others append, join, copy etc.
7
Data Representation Methods
  • Formula based
  • Use a math formula to determine where to store
    each element of a list
  • Ex Successive elements of a list in successive
    memory locations (sequential representation of a
    list)
  • Linked or pointer based
  • Elements of a list may be stored in any arbitrary
    set of memory locations
  • Each element has an explicit pointer (or link)
    that tells us the location of the next element in
    the list
  • Indirect addressing
  • Elements of a list may be stored in any arbitrary
    set of memory locations
  • Maintain a table with i th table entry telling
    where the i th list element is
  • Simulated pointer
  • Ignore?

8
Arrays Representation
Element 0 1 2 3 MaxSize-1
5
2
4
3
4
8
9
1
Representation location (i) i-1
9
Arrays Operations
Create() Destroy() IsEmpty() Length() Find(k) Sear
ch(x) Delete(k,x) Insert(k,x)
Array elements MaxSize Length
10
Arrays Inefficient use of space
Element 0 1 2 3 MaxSize-1
Length2
5
2
Example Consider we need 3 lists Together will
never have more than 5000 elements Each list may
have up to 5000 elements at some time or the
other Simple implementation Need 15,000
elements ? INEFFICIENT
11
Arrays Space Efficiency
One Possible Solution Represent lists in a
single array Use two additional arrays first and
last to index into this one
For accuracy, always check for the
boundary/extreme conditions!
  • What if list 2 is empty?
  • How to add elements to list 2 when there is no
    additional space between list 2 and 3? What if we
    cannot shift list 3? Need to move up or down? ?
    Insertions take more time (at least in worst case)

12
Array Limitations
  • Arrays
  • Simple,
  • Fast
  • but
  • Must specify size at construction time
  • Murphys law
  • Construct an array with space for n
  • n twice your estimate of largest collection
  • Tomorrow youll need n1
  • More flexible system?

13
Dynamic Array?
  • Insert Operation
  • If we already have MaxSize elements in the list
  • Allocate a new array with double the MaxSize
  • Copy the elements from old array to new one
  • Delete the old array
  • Delete Operation
  • If the list size drops to one-fourth of the
    current MaxSize
  • Create a smaller array of size MaxSize/2
  • Elements are copied and old array is deleted
  • Even more flexible system?

14
Linked Lists
  • Flexible space use
  • Dynamically allocate space for each element as
    needed
  • Include a pointer to the next item
  • Linked list
  • Each node of the list contains
  • the data item (an object pointer in our ADT)
  • a pointer to the next node

Data
Next
object
15
Linked Lists
  • Collection structure has a pointer to the list
    head
  • Initially NULL

Also called as singly linked list
16
Linked Lists
  • Add second item (say in the front of the list)
  • Allocate space for node
  • Set its data pointer to object
  • Set Next to current Head
  • Set Head to point to new node

Head
Collection
node
node
17
Linked Lists - Add implementation
  • Implementation

struct t_node void item struct t_node
next node typedef struct t_node
Node struct collection Node head
int AddToCollection( Collection c, void
item ) Node new malloc( sizeof( struct
t_node ) ) new-gtitem item new-gtnext
c-gthead c-gthead new return TRUE

Where is initialization for head?
18
Linked Lists
  • Add time (for each element)
  • Constant - independent of n (n is the size of the
    existing linked list)
  • Search time
  • Worst case - n

Head
node
node
Collection
19
Linked Lists - Find implementation
  • Implementation

void FindinCollection( Collection c, void key
) Node n c-gthead while ( n ! NULL )
if ( KeyCmp( ItemKey( n-gtitem ), key ) 0 )
return n-gtitem n n-gtnext
return NULL
What is missing? What to return? What more is
generally required?
A recursive implementation is also possible!
20
Linked Lists - Delete implementation
  • Implementation

void DeleteFromCollection( Collection c, void
key ) Node n, prev n prev
c-gthead while ( n ! NULL ) if ( KeyCmp(
ItemKey( n-gtitem ), key ) 0 ) prev-gtnext
n-gtnext return n prev
n n n-gtnext return NULL

head
For accuracy, always check for the
boundary/extreme conditions!
21
Linked Lists - Delete implementation
  • Implementation

void DeleteFromCollection( Collection c, void
key ) Node n, prev n prev
c-gthead while ( n ! NULL ) if ( KeyCmp(
ItemKey( n-gtitem ), key ) 0 ) prev-gtnext
n-gtnext return n prev
n n n-gtnext return NULL

What if more than one node matches the criteria?
head
Minor addition needed to allow for deleting this
one! An exercise!
22
Linked Lists - LIFO and FIFO
  • Simplest implementation
  • Add to head
  • Last-In-First-Out (LIFO) semantics
  • Modifications
  • First-In-First-Out (FIFO)
  • Keep a tail pointer

head
struct t_node void item struct t_node
next node typedef struct t_node
Node struct collection Node head, tail

tail
tail is set in the AddToCollection method if head
NULL
23
Linked Lists - Doubly linked
  • Doubly linked lists
  • Can be scanned in both directions

struct t_node void item struct t_node
prev, next
node typedef struct t_node Node struct
collection Node head, tail
head
prev
prev
prev
tail
24
Linked Lists Circular List
head
Simpler and sometimes faster
25
Performance?
26
Arrays Vs. Linked Lists
  • Space
  • Array Need only as much space as needed to store
    the elements plus the list length (at least when
    size is not changing!)
  • Chain and circular list requires additional space
    for link field
  • One link field for every element in the list
  • Performance
  • Run time for insert and delete are smaller with
    linked representation
  • Can access kth element of a list in O(1) time,
    where as in linked lists we need O(k) time.
  • Multiple instances
  • Linked representation can be used for many lists
    with no degradation in space or performance
  • Array representation to use space more
    efficiently, need to represent all lists in
    single array and use additional arrays to indexed
    into this one.
  • Insertion and deletion are more complex

27
Indirect Addressing
  • Combination of Arrays and Linked representation
  • Retain many advantages of both worlds
  • Ex Access elements in O(1) time
  • Array of pointers to the list elements (formula
    based)
  • Elements are stored in dynamically allocated nodes

4
  • Table provides one level of indirection in the
    addressing scheme
  • Pointers are in table

5
8
2
Table Length4
0 1 2 3
28
A Comparison
s size of the array/list n lest length
Same space requirements as linked list
29
Arrays
  • Array has (index, value) index is unique
  • Indexing an Array
  • int score u1u2u3..uk
  • iscorei1i2..ik
  • Memory size (nu1u2..uk) units

30
Arrays Matrices
  • Arrays are most natural way to represent tabular
    data
  • Can we reduce time and space requirements?
  • Especially when large fraction of table entries
    are zero

31
Row- and Column-Major Mappings
  • Internally stored in an array of size n
  • Given indices can be mapped to exact location or
    vice versa
  • C C uses Row-major mapping
  • Number the indexes by row beginning with the
    first row, within each row numbers are assigned
    from left to right

0 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17
0 3 6 9 12 15 1 4 7 10 13
16 2 5 8 11 14 17
Row-major
Column-major
Row-major mapping function map(i1,i2) i1u2
i2
32
C and C
  • Array support is primitive
  • Does not validate array subscripts
  • Permitted to use array indexes that are outside
    the declared range
  • Cannot perform add and subtract operations even
    on one-dimensional arrays
  • No support for output and input of arrays
  • Does not support i, j notation, but only ij
    notation
  • C class can be included
  • Constructor, copy constructor, destructor,
    indexing operator , size function, ,-,,and .

33
Matrix Operations
  • Transpose
  • MT(I,,j) M(j,I), 1lti lt n, 1 lt j lt m
  • Addition or Sum
  • C(i,j) A (i,j) B(i,j), 1lt i lt n, 1 lt j lt
    m
  • Multiplication or Product
  • C(i,j) S A (i,k) B(k,j), 1lt i lt m, 1 lt j
    lt p
  • (mXp) (mXn) (nXp)

n
k1
34
Special Matrices
  • Square Same number of rows and columns
  • Diagonal
  • M(i,j) 0 for i not equal to j
  • Tridiagonal
  • M(i,j) 0 for i-j gt 1
  • Lower triangular
  • M(i,j) 0 for i lt j
  • Upper traingular
  • M(i,j) 0 for i gt j
  • Symmetric
  • M(i,j) M(j,i) for for all i, j

35
Special Matrices
  • Diagonal Matrix
  • Memory efficient representation dn
  • Tridiagonal Matrix
  • Main diagonal (Ij)
  • Diagonal below main diagonal (Ij1)
  • Diagonal above main diagonal (I j-1)
  • Triangular Matrices
  • Need one dimensional array of size n(n1)/2
  • Need to have a mapping
  • Symmetric Matrices
  • Need only n(n1)/2 array Store either the lower
    or upper triangle of the matrix

36
Sparse Matrices
  • mXn matrix is sparse if many of its elements are
    zero (not dense)
  • Diagonal and Tridiagonal matrices have sufficient
    structure in their nonzero regions ? simple
    representation scheme
  • Now irregularity and unstructured nonzero region
  • Array representation

0 0 0 2 0 0 1 0 0 6 0 0 7 0 0 3 0
0 0 9 0 8 0 0 0 4 5 0 0 0 0 0
37
Sparse Matrix Operations
  • Matrix Transpose How?
  • Addition of Two matrices How?
  • Shortcomings?
  • Need to know the nonzero terms to create an array
  • We do not know the size accurately when we are
    doing additions, multiplications of matrices etc.
  • Can throw exceptions ? Need to recreate a larger
    array and redo the job!
  • Other option Linked representation

38
Linked Representation
col link
col link
row a.first
1
4
2
7
1
0
value
value
2
2
6
5
7
8
3
0
3
4
9
6
8
0
4
0
2
4
3
5
0
39
Next Time
  • Stacks Queues
  • Student TalkWho?
Write a Comment
User Comments (0)
About PowerShow.com