SlideShare a Scribd company logo
Lists
Data Structures and Algorithm Analysis in C, by Mark Allen Weiss, 2nd
edition, 1997, Addison-Wesley, ISBN 0-201-49840-5
Danang University of Science and Technology
Dang Thien Binh
dtbinh@dut.udn.vn
Data Structures
Readings and References
 Reading
 Sections 3.1 - 3.2.8, Data Structures and Algorithm Analysis in C,
Weiss
 Other References
2
Data Structures
Review: Pointers and Memory
 Recall that memory is a one-dimensional array of
bytes, each with an address
 Pointer variables contain an address
3
int y, *aP, *bP; // pointer vars use * in declaration
y = 3;
aP = &y;
*aP = 17;
printf("aP: %pn",aP);
printf("*aP = %dn",y); // prints out what?
printf("bP: %pn",bP);
*bP = 1; // what happens? (hint: DOOM)
Data Structures
Example result
4
#include <stdio.h>
int main(int argc, char *argv[]) {
int y, *aP, *bP; // pointer vars use * in declaration
y = 3;
aP = &y;
*aP = 17;
printf("aP: %pn",aP);
printf("*aP = %dn",y); // prints out what?
printf("bP: %pn",bP);
*bP = 1; // what happens? (hint: DOOM)
return 0;
}
aP: 0xbffffa54
*aP = 17
bP: 0x8048441
Segmentation fault (core dumped)
Data Structures
Review: Memory Management
 Use “malloc” to allocate a specified number of bytes for
new variables
aP = (int *) malloc(sizeof(int));
 Use the sizeof operator to compute the number of bytes needed for
the data type
 malloc does not initialize the memory
 To deallocate memory, use “free” and pass a pointer to an
object allocated with malloc
free(aP);
5
Data Structures
List ADT
 What is a List?
 Ordered sequence of elements A1, A2, …, AN
 Elements may be of arbitrary type, but all are the same
type
 Common List operations are
 Insert, Find, Delete, IsEmpty, IsLast, FindPrevious, First, Kth, Last
6
Data Structures
List Implementations
 Two types of implementation:
 Array-Based
 Pointer-Based
7
Data Structures
List: Array Implementation
 Basic Idea:
 Pre-allocate a big array of size MAX_SIZE
 Keep track of current size using a variable count
 Shift elements when you have to insert or delete
8
AN
…
A4
A3
A2
A1
MAX_SIZE-1
count-1
…
3
2
1
0
Data Structures
List: Array Implementation
typedef struct _ListInfo (
ElementType *theArray; //= malloc(MAX_SIZE*sizeof(ElementType))
int count; // = 0
int maxsize; //=MAX_SIZE
}
typedef ListInfo *List;
typedef int Position;
//Empty list has allocated array and count = 0
Need to define: void Insert(List L, ElementType E, Position P)
// Example: Insert E at position P = 2
9
AN
…
A4
A3
A2
A1
MAX_SIZE-1
count-1
…
3
2
1
0
Data Structures
Array List Insert Operation
 Basic Idea: Insert new item and shift old items
to the right.
10
void Insert(List L, ElementType e, Position p) {
Position current;
if (p > L->count || L->count == MAX_SIZE) exit(1);
current = L->count;
while (current != p) {
L->a[current] = L->a[current-1];
current--;
}
L->a[current] = e;
L->count++;
}
Data Structures
Array List Insert Running Time
 Running time for N elements?
 On average, must move half the elements to
make room
 Worst case is insert at position 0. Must move
all N items down one position before the
insert
 This is O(N) running time.
11
Data Structures
List: Pointer Implementation
 Basic Idea:
 Allocate little blocks of memory (nodes) as elements are add
ed to the list
 Keep track of list by linking the nodes together
 Change links when you want to insert or delete
12
Value
NULL
pL
node
Value Next
node
Next
Data Structures
List: A Pointer Implementation
struct Node {
ElementType Value;
struct Node *next;
};
typedef struct Node *List;
typedef struct Node *Position;
// Pointer to an empty list = NULL
void Insert(List *pL, ElementType E, Position P)
// Insert adds new node after the one pointed to by P
// if P is NULL or list is empty (pL=NULL), insert at beginning of l
ist
13
Data Structures
Pointer-Based Linked List
14
Value
NULL
pL
node
Value Next
node
Next
Data Structures
List: A Pointer Implementation
// Insert adds new node after the one pointed to by P
// if P is NULL or list is empty, insert at beginning of list
void Insert(List *pL, ElementType E, Position P)
Position newItem;
newItem = (struct Node *)malloc(sizeof(struct Node));
FatalErrorMemory(newItem);
newItem->Value = E;
if (pL == NULL || P == NULL) { //insert at head of list
newItem->next = pL;
pL = newItem;
}
else { // insert newItem after the node pointed to by P
newItem->next = P->next;
P->next = newItem;
}
15
Data Structures
Pointer-based Insert Operation
16
Value
NULL
pL
node
Value Next
node
P
Insert the value E after P
Next
Value
E
Next
Data Structures
Using a Header Node
 If the List pointer points to first item, then
 any change in first item changes List itself
 need special checks if List pointer is NULL
 L->next is invalid (L is not a Node struct)
 Solution: Use “header node” at beginning of all lists (see te
xt)
 List pointer always points to header node, which points t
o first actual list item
 Simplifies the code, but you need to remember that ther
e is an "empty" node at the start of the list
17
Data Structures
Linked List with Header Node
18
Value Next
pL
first actual list node
Value
ignore
Next
header node
NULL
Data Structures
Pointer Implementation Issues
 Whenever you break a list, your code should fix the list
up as soon as possible
 Draw pictures of the list to visualize what needs to be done
 Pay special attention to boundary conditions:
 Empty list
 Single item – same item is both first and last
 Two items – first, last, but no middle items
 Three or more items – first, last, and middle items
19
Data Structures
Pointer List Insert Running Time
 Running time for N elements?
 Insert takes constant time (O(1))
 Does not depend on input size
 Compare to array bases list which is O(N)
20
Data Structures
Pointer-Based Linked List Delete
21
Value Next
pL
node
Value Next
node
P
To delete the node pointed to by P,
need a pointer to the previous node
NULL
Data Structures
Doubly Linked Lists
 FindPrev (and hence Delete) is slow because
we cannot go directly to previous node
 Solution: Keep a "previous" pointer at each nod
e
22
head prev prev prev
Data Structures
Double Link Pros and Cons
 Advantage
 Delete and FindPrev are fast like Insert is
 Disadvantages:
 More space used up (double the number of pointers at
each node)
 More book-keeping for updating the two pointers at eac
h node
23
Data Structures
Circularly Linked Lists
 Set the pointer of the last node to first node instead of NUL
L
 Useful when you want to iterate through whole list starting f
rom any node
 No need to write special code to wrap around at the end
 Circular doubly linked lists speed up both the Delete and L
ast operations
24
Data Structures
Polynomial ADT
 Store and manipulate single variable polynomials with non-
negative exponents
 10x3 + 4x2 + 7 ( = 10x3 + 4 x2 + 0 x1 + 7 x0 )
 Store coefficients Ci and exponents i
 ADT operations
 Addition: C[i] = A[i] + B[i];
 Multiplication: C[i+j] = C[i+j] + A[i]*B[j];
25
Data Structures
Polynomial Implementation
 Array Implementation: C[i] = Ci
 E.g. C[3] = 10, C[2] = 4, C[1] = 0, C[0] = 7
 Problem with Array implementation
 High-order sparse polynomials require large sparse arrays
 E.g. 10X3000 + 4 X2+ 7  Waste of space and time (Ci are mostly
0s)
 Instead, use singly linked lists, sorted in decreasing order
of exponents
26
Data Structures
Bucket Sort: Sorting integers
 Bucket sort: N integers in the range 0 to B-1
 Array Count has B elements (“buckets”), initialized to 0
 Given input integer i, Count[i]++
 After reading all N numbers go through the B buckets and read
out the resulting sorted list
 N operations to read and record the numbers plus B operations
to recover the sorted numbers
27
Data Structures
Radix Sort: Sorting integers
 Radix sort = multi-pass bucket sort of integers in the
range 0 to BP-1
 Bucket-sort from least significant to most significant "digit"
(base B)
 Use linked list to store numbers that are in same bucket
 Requires P*(B+N) operations where P is the number of passes
(the number of base B digits in the largest possible input
number)
28

More Related Content

PPTX
Module 1 Intro to Data Structures CSE 1101.pptx
bansidhar11
 
PPT
1. Data structures introduction
Mandeep Singh
 
PPTX
8.DATA STRUCTURES UNIT 1 AND 2 CS3301PPT.pptx
venigkrish89
 
PDF
2a-Linked Listsxcxxcxxcxcxcxcxcxcxcxcxx.pdf
NGUYNTHNHQUC2
 
PPT
Intro_2.ppt
MumitAhmed1
 
PPT
Intro.ppt
Anonymous9etQKwW
 
PPT
Intro.ppt
SharabiNaif
 
PDF
Data and File Structure Lecture Notes
FellowBuddy.com
 
Module 1 Intro to Data Structures CSE 1101.pptx
bansidhar11
 
1. Data structures introduction
Mandeep Singh
 
8.DATA STRUCTURES UNIT 1 AND 2 CS3301PPT.pptx
venigkrish89
 
2a-Linked Listsxcxxcxxcxcxcxcxcxcxcxcxx.pdf
NGUYNTHNHQUC2
 
Intro_2.ppt
MumitAhmed1
 
Intro.ppt
Anonymous9etQKwW
 
Intro.ppt
SharabiNaif
 
Data and File Structure Lecture Notes
FellowBuddy.com
 

Similar to 03-Lists.ppt (20)

PPTX
introduction_dst.pptx
HammadTariq51
 
PPT
Data Structure Lec #1
University of Gujrat, Pakistan
 
PPTX
Data structures and algorithms
Julie Iskander
 
PPT
CS301-lec01.ppt
omair31
 
PPTX
2.02.Data_structures_and_algorithms (1).pptx
DrBashirMSaad
 
PPTX
Linked List Data structure using C programming and all the detailed informat...
meenaka Rajendran
 
PPTX
Linked lists a
Khuram Shahzad
 
PPT
Lecture 1 IntroductionToDataStructures_coursematerial_Draft0.01.ppt
iamsallauddin
 
PPTX
Data structures - unit 1
SaranyaP45
 
PPTX
Data Structures - Unit 1 linked list
RajeswariA8
 
PPTX
EC2311 – Data Structures and C Programming
Padma Priya
 
PDF
4 chapter3 list_stackqueuepart1
SSE_AndyLi
 
PPTX
Data Structure & aaplications_Module-1.pptx
GIRISHKUMARBC1
 
PPT
DS_PPT.ppt
MeghaKulkarni27
 
PPTX
DATA STRUCTURE AND ALGORITHM with linked list
shanmugapriyacsecs
 
PPTX
Introduction to Data Structure
chouguleamruta24
 
PPT
Data structures cs301 power point slides lecture 01
shaziabibi5
 
PPT
Data structure and algorithm with java by shikra
jateno3396
 
PPT
Linked list introduction and different operation
HODCSE170941
 
PPTX
UNIT I LINEAR DATA STRUCTURES – LIST .pptx
VISWANATHAN R V
 
introduction_dst.pptx
HammadTariq51
 
Data Structure Lec #1
University of Gujrat, Pakistan
 
Data structures and algorithms
Julie Iskander
 
CS301-lec01.ppt
omair31
 
2.02.Data_structures_and_algorithms (1).pptx
DrBashirMSaad
 
Linked List Data structure using C programming and all the detailed informat...
meenaka Rajendran
 
Linked lists a
Khuram Shahzad
 
Lecture 1 IntroductionToDataStructures_coursematerial_Draft0.01.ppt
iamsallauddin
 
Data structures - unit 1
SaranyaP45
 
Data Structures - Unit 1 linked list
RajeswariA8
 
EC2311 – Data Structures and C Programming
Padma Priya
 
4 chapter3 list_stackqueuepart1
SSE_AndyLi
 
Data Structure & aaplications_Module-1.pptx
GIRISHKUMARBC1
 
DS_PPT.ppt
MeghaKulkarni27
 
DATA STRUCTURE AND ALGORITHM with linked list
shanmugapriyacsecs
 
Introduction to Data Structure
chouguleamruta24
 
Data structures cs301 power point slides lecture 01
shaziabibi5
 
Data structure and algorithm with java by shikra
jateno3396
 
Linked list introduction and different operation
HODCSE170941
 
UNIT I LINEAR DATA STRUCTURES – LIST .pptx
VISWANATHAN R V
 
Ad

Recently uploaded (20)

PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PPT
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
Information Retrieval and Extraction - Module 7
premSankar19
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Ad

03-Lists.ppt

  • 1. Lists Data Structures and Algorithm Analysis in C, by Mark Allen Weiss, 2nd edition, 1997, Addison-Wesley, ISBN 0-201-49840-5 Danang University of Science and Technology Dang Thien Binh [email protected]
  • 2. Data Structures Readings and References  Reading  Sections 3.1 - 3.2.8, Data Structures and Algorithm Analysis in C, Weiss  Other References 2
  • 3. Data Structures Review: Pointers and Memory  Recall that memory is a one-dimensional array of bytes, each with an address  Pointer variables contain an address 3 int y, *aP, *bP; // pointer vars use * in declaration y = 3; aP = &y; *aP = 17; printf("aP: %pn",aP); printf("*aP = %dn",y); // prints out what? printf("bP: %pn",bP); *bP = 1; // what happens? (hint: DOOM)
  • 4. Data Structures Example result 4 #include <stdio.h> int main(int argc, char *argv[]) { int y, *aP, *bP; // pointer vars use * in declaration y = 3; aP = &y; *aP = 17; printf("aP: %pn",aP); printf("*aP = %dn",y); // prints out what? printf("bP: %pn",bP); *bP = 1; // what happens? (hint: DOOM) return 0; } aP: 0xbffffa54 *aP = 17 bP: 0x8048441 Segmentation fault (core dumped)
  • 5. Data Structures Review: Memory Management  Use “malloc” to allocate a specified number of bytes for new variables aP = (int *) malloc(sizeof(int));  Use the sizeof operator to compute the number of bytes needed for the data type  malloc does not initialize the memory  To deallocate memory, use “free” and pass a pointer to an object allocated with malloc free(aP); 5
  • 6. Data Structures List ADT  What is a List?  Ordered sequence of elements A1, A2, …, AN  Elements may be of arbitrary type, but all are the same type  Common List operations are  Insert, Find, Delete, IsEmpty, IsLast, FindPrevious, First, Kth, Last 6
  • 7. Data Structures List Implementations  Two types of implementation:  Array-Based  Pointer-Based 7
  • 8. Data Structures List: Array Implementation  Basic Idea:  Pre-allocate a big array of size MAX_SIZE  Keep track of current size using a variable count  Shift elements when you have to insert or delete 8 AN … A4 A3 A2 A1 MAX_SIZE-1 count-1 … 3 2 1 0
  • 9. Data Structures List: Array Implementation typedef struct _ListInfo ( ElementType *theArray; //= malloc(MAX_SIZE*sizeof(ElementType)) int count; // = 0 int maxsize; //=MAX_SIZE } typedef ListInfo *List; typedef int Position; //Empty list has allocated array and count = 0 Need to define: void Insert(List L, ElementType E, Position P) // Example: Insert E at position P = 2 9 AN … A4 A3 A2 A1 MAX_SIZE-1 count-1 … 3 2 1 0
  • 10. Data Structures Array List Insert Operation  Basic Idea: Insert new item and shift old items to the right. 10 void Insert(List L, ElementType e, Position p) { Position current; if (p > L->count || L->count == MAX_SIZE) exit(1); current = L->count; while (current != p) { L->a[current] = L->a[current-1]; current--; } L->a[current] = e; L->count++; }
  • 11. Data Structures Array List Insert Running Time  Running time for N elements?  On average, must move half the elements to make room  Worst case is insert at position 0. Must move all N items down one position before the insert  This is O(N) running time. 11
  • 12. Data Structures List: Pointer Implementation  Basic Idea:  Allocate little blocks of memory (nodes) as elements are add ed to the list  Keep track of list by linking the nodes together  Change links when you want to insert or delete 12 Value NULL pL node Value Next node Next
  • 13. Data Structures List: A Pointer Implementation struct Node { ElementType Value; struct Node *next; }; typedef struct Node *List; typedef struct Node *Position; // Pointer to an empty list = NULL void Insert(List *pL, ElementType E, Position P) // Insert adds new node after the one pointed to by P // if P is NULL or list is empty (pL=NULL), insert at beginning of l ist 13
  • 14. Data Structures Pointer-Based Linked List 14 Value NULL pL node Value Next node Next
  • 15. Data Structures List: A Pointer Implementation // Insert adds new node after the one pointed to by P // if P is NULL or list is empty, insert at beginning of list void Insert(List *pL, ElementType E, Position P) Position newItem; newItem = (struct Node *)malloc(sizeof(struct Node)); FatalErrorMemory(newItem); newItem->Value = E; if (pL == NULL || P == NULL) { //insert at head of list newItem->next = pL; pL = newItem; } else { // insert newItem after the node pointed to by P newItem->next = P->next; P->next = newItem; } 15
  • 16. Data Structures Pointer-based Insert Operation 16 Value NULL pL node Value Next node P Insert the value E after P Next Value E Next
  • 17. Data Structures Using a Header Node  If the List pointer points to first item, then  any change in first item changes List itself  need special checks if List pointer is NULL  L->next is invalid (L is not a Node struct)  Solution: Use “header node” at beginning of all lists (see te xt)  List pointer always points to header node, which points t o first actual list item  Simplifies the code, but you need to remember that ther e is an "empty" node at the start of the list 17
  • 18. Data Structures Linked List with Header Node 18 Value Next pL first actual list node Value ignore Next header node NULL
  • 19. Data Structures Pointer Implementation Issues  Whenever you break a list, your code should fix the list up as soon as possible  Draw pictures of the list to visualize what needs to be done  Pay special attention to boundary conditions:  Empty list  Single item – same item is both first and last  Two items – first, last, but no middle items  Three or more items – first, last, and middle items 19
  • 20. Data Structures Pointer List Insert Running Time  Running time for N elements?  Insert takes constant time (O(1))  Does not depend on input size  Compare to array bases list which is O(N) 20
  • 21. Data Structures Pointer-Based Linked List Delete 21 Value Next pL node Value Next node P To delete the node pointed to by P, need a pointer to the previous node NULL
  • 22. Data Structures Doubly Linked Lists  FindPrev (and hence Delete) is slow because we cannot go directly to previous node  Solution: Keep a "previous" pointer at each nod e 22 head prev prev prev
  • 23. Data Structures Double Link Pros and Cons  Advantage  Delete and FindPrev are fast like Insert is  Disadvantages:  More space used up (double the number of pointers at each node)  More book-keeping for updating the two pointers at eac h node 23
  • 24. Data Structures Circularly Linked Lists  Set the pointer of the last node to first node instead of NUL L  Useful when you want to iterate through whole list starting f rom any node  No need to write special code to wrap around at the end  Circular doubly linked lists speed up both the Delete and L ast operations 24
  • 25. Data Structures Polynomial ADT  Store and manipulate single variable polynomials with non- negative exponents  10x3 + 4x2 + 7 ( = 10x3 + 4 x2 + 0 x1 + 7 x0 )  Store coefficients Ci and exponents i  ADT operations  Addition: C[i] = A[i] + B[i];  Multiplication: C[i+j] = C[i+j] + A[i]*B[j]; 25
  • 26. Data Structures Polynomial Implementation  Array Implementation: C[i] = Ci  E.g. C[3] = 10, C[2] = 4, C[1] = 0, C[0] = 7  Problem with Array implementation  High-order sparse polynomials require large sparse arrays  E.g. 10X3000 + 4 X2+ 7  Waste of space and time (Ci are mostly 0s)  Instead, use singly linked lists, sorted in decreasing order of exponents 26
  • 27. Data Structures Bucket Sort: Sorting integers  Bucket sort: N integers in the range 0 to B-1  Array Count has B elements (“buckets”), initialized to 0  Given input integer i, Count[i]++  After reading all N numbers go through the B buckets and read out the resulting sorted list  N operations to read and record the numbers plus B operations to recover the sorted numbers 27
  • 28. Data Structures Radix Sort: Sorting integers  Radix sort = multi-pass bucket sort of integers in the range 0 to BP-1  Bucket-sort from least significant to most significant "digit" (base B)  Use linked list to store numbers that are in same bucket  Requires P*(B+N) operations where P is the number of passes (the number of base B digits in the largest possible input number) 28