Data Structures Linked list.

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Arrays: pluses and minuses + Fast element access. -- Impossible to resize.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Linked Lists Definition of Linked Lists Examples of Linked Lists
DATA STRUCTURES USING C++ Chapter 5
Linked lists CSCI 2170.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
3 May Linked Lists CSE 2011 Winter Linked Lists2 Singly Linked Lists (3.2) A singly linked list is a concrete data structure consisting of.
Data Structures Lecture 4 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
© 2004 Goodrich, Tamassia Lists1. © 2004 Goodrich, Tamassia Lists2 Position ADT (§ 5.2.2) The Position ADT models the notion of place within a data structure.
Linked Lists1 Part-B3 Linked Lists. Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data structure consisting of a sequence.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
Linked Lists1 Part-B3 Linked Lists. Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data structure consisting of a sequence.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
Chapter 3: Arrays, Linked Lists, and Recursion
CS212D : DATA STRUCTURES 1 Week 5-6 Linked List. Outline 2  Singly Linked Lists  Doubly Linked Lists  Recursions.
CS 1031 Linked Lists Definition of Linked Lists Examples of Linked Lists Operations on Linked Lists Linked List as a Class Linked Lists as Implementations.
Mohammad Amin Kuhail M.Sc. (York, UK) University of Palestine Faculty of Engineering and Urban planning Software Engineering Department Computer Science.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Lecture 3 Queues Queues1. queue: – Retrieves elements in the order they were added. – First-In, First-Out ("FIFO") – Elements are stored in order of insertion.
Lecture5: Linked Lists Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
1 Linked Lists (Lec 6). 2  Introduction  Singly Linked Lists  Circularly Linked Lists  Doubly Linked Lists  Multiply Linked Lists  Applications.
© 2004 Goodrich, Tamassia Lists1. © 2004 Goodrich, Tamassia Lists2 Position ADT (§ 5.2.2) The Position ADT models the notion of place within a data structure.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Introduction Dynamic Data Structures Grow and shrink at execution time Linked lists are dynamic structures where data items are “linked up in a chain”
1 Queues and Lists. QUEUES Very similar to stacks The only difference between them is in the order in which elements are processed. A stack uses a last-in/first-out.
1 Midterm 1 on Friday February 12 Closed book, closed notes No computer can be used 50 minutes 4 questions Write a function Write program fragment Explain.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Linked List, Stacks Queues
Lecture 6 of Computer Science II
Review Array Array Elements Accessing array elements
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Vectors 5/31/2018 9:25 AM Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and.
Lectures linked lists Chapter 6 of textbook
Linked Lists Chapter 6 Section 6.4 – 6.6
Sequences 6/3/2018 9:11 AM Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia,
Data Structure Dr. Mohamed Khafagy.
Data Structures and Algorithms
Sequences 8/1/2018 4:38 AM Linked Lists Linked Lists.
Chapter 4 Linked Lists.
Sequences 8/2/ :13 AM Linked Lists Linked Lists.
Sequences 8/2/ :16 AM Linked Lists Linked Lists.
EEL 4854 IT Data Structures Linked Lists
Queues Queues Queues.
Chapter 4 Linked Lists
Linked List Sudeshna Sarkar.
LINKED LISTS CSCD Linked Lists.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Lists.
Chapter 4 Linked Lists.
Sequences 11/27/2018 1:37 AM Singly Linked Lists Singly Linked Lists.
Linked Lists.
Sequences 12/8/2018 3:02 AM Linked Lists Linked Lists.
CS212D: Data Structures Week 5-6 Linked List.
CS2013 Lecture 4 John Hurley Cal State LA.
Doubly Linked List Implementation
Data Structures and Algorithms
Problem Understanding
Chapter 4 Linked Lists.
Linked List.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Linked Lists & Iterators
LAB#4 Linked List.
CS210- Lecture 6 Jun 13, 2005 Announcements
CS210- Lecture 7 Jun 14, 2005 Agenda Practice Session Vector
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Problem Understanding
Presentation transcript:

Data Structures Linked list

Pointer-Based Linked Lists A node in a linked list is usually a struct struct Node { int item Node *next; }; //end struct A node is dynamically allocated Node *p; p = new Node;

Pointer-Based Linked Lists Figure 4.7 A head pointer to a list Figure 4.8 A lost cell

Back To Stacks val Stack Top Return value typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Node* constructNode(int val) { Node * p=(Node *)malloc(sizeof(Node)); p->item=val; p->next=NULL; return p; } void initialize(Stack *s) { s->Top=NULL; val Return value Stack Top

Back To Stacks void push(Stack *s,TYPE value) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE value) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } p value

Back To Stacks void push(Stack *s,TYPE value) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE value) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } p value

Back To Stacks void push(Stack *s,TYPE val1) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE val1) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } val1

Back To Stacks void push(Stack *s,TYPE val2) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE val2) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } val2 val1

Back To Stacks void push(Stack *s,TYPE val2) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE val2) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } val2 val1

Back To Stacks void push(Stack *s,TYPE val2) { typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top void push(Stack *s,TYPE val2) { Node *p=constructNode(value); p->next=s->Top; s->Top=p; } val2 val1

Back To Stacks p TYPE pop(Stack *s) { Node *p=s->Top; typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top TYPE pop(Stack *s) { Node *p=s->Top; TYPE ret=p->item; s->Top=p->next; free(p); return ret; } p val2 val1 ret=val2

Back To Stacks p TYPE pop(Stack *s) { Node *p=s->Top; typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top TYPE pop(Stack *s) { Node *p=s->Top; TYPE ret=p->item; s->Top=p->next; free(p); return ret; } p val2 val1 ret=val2

Back To Stacks p TYPE pop(Stack *s) { Node *p=s->Top; typedef struct Node Node; typedef struct Node { int item; Node * next; } Node; typedef struct { Node * Top; } Stack; Stack Top TYPE pop(Stack *s) { Node *p=s->Top; TYPE ret=p->item; s->Top=p->next; free(p); return ret; } p val2 val1 ret=val2

Definition of Linked Lists A linked list is a sequence of items (objects) where every item is linked to the next. Graphically: data head_ptr tail_ptr

Definition Details Each item has a data part (one or more data members), and a link that points to the next item One natural way to implement the link is as a pointer; that is, the link is the address of the next item in the list It makes good sense to view each item as an object, that is, as an instance of a class. We call that class: Node The last item does not point to anything. We set its link member to NULL. This is denoted sometimes graphically by a self-loop

Examples of Linked Lists (A Waiting Line) A waiting line of customers: John, Mary, Dan, Sue (from the head to the tail of the line) A linked list of strings can represent this line: John Mary Dan Sue tail_ptr head_ptr

Examples of Linked Lists (A Stack of Numbers) A stack of numbers (from top to bottom): 10, 8, 6, 8, 2 A linked list of ints can represent this stack: 10 8 6 8 2 head_ptr tail_ptr

Examples of Linked Lists (A Set of Non-redundant Elements) A set of characters: a, b, d, f, c A linked list of chars can represent this set: a b d f c head_ptr tail_ptr

Examples of Linked Lists (A Sorted Set of Non-redundant Elements) A set of characters: a, b, d, f, c The elements must be arranged in sorted order: a, b, c, d, f A linked list of chars can represent this set: a b c d f tail_ptr head_ptr

Examples of Linked Lists (A Polynomial) A polynomial of degree n is the function Pn(x)=a0+a1x+a2x2+…+anxn. The ai’s are called the coefficients of the polynomial The polynomial can be represented by a linked list (2 data members and a link per item): a0,0 a1,1 a2,2 an,n tail_ptr head_ptr

Operations on Linked Lists Insert a new item At the head of the list, or At the tail of the list, or Inside the list, in some designated position Search for an item in the list The item can be specified by position, or by some value Delete an item from the list Search for and locate the item, then remove the item, and finally adjust the surrounding pointers size( ); isEmpty( )

Insert– At the Head Insert a new data A. Call new: newPtr List before insertion: After insertion to head: data data data data head_ptr tail_ptr A data head_ptr tail_ptr The link value in the new item = old head_ptr The new value of head_ptr = newPtr

Insert – at the Tail Insert a new data A. Call new: newPtr List before insertion After insertion to tail: data data data data head_ptr tail_ptr data A tail_ptr head_ptr The link value in the new item = NULL The link value of the old last item = newPtr

Implementing a linked list #define TYPE int typedef struct { TYPE data; struct Node *next; } Node; Node * newNode(TYPE value) { Node *n=malloc(sizeof(Node)); n->data=value; n->next=NULL; return n; } Node *head, *tail; } LinkedList; void initLinkedList(LinkedList *ll){ll->head=NULL;ll->tail=NULL;}

Implementing a linked list void printLinkedList(Node *n){ printf("["); while (n) {printf("%d ",n->data);n=(Node *)n->next;} printf("]\n"); } void addHead(LinkedList *ll,TYPE value) { Node *n=newNode(value); n->next=ll->head; ll->head=n; if(!ll->tail) ll->tail=n; //list was empty void addTail(LinkedList *ll,TYPE value) { Node *n=newNode(value);Node *tail=ll->tail; ll->tail=n; if (tail) tail->next=n; else ll->head=n; // TAIL is NULL so is head!

Implementing a linked list int main() { LinkedList ll;initLinkedList(&ll); printLinkedList(ll.head); addTail(&ll,1);addHead(&ll,5);addHead(&ll,6);addTail(&ll,7); return 0; } [] [6 5 1 7 ]

Delete – the Head Item List before deletion: List after deletion of the head item: data data data data data tail_ptr head_ptr data data data data data head_ptr tail_ptr The new value of head_ptr = link-value of the old head item The old head item is deleted and its memory returned

Implementing a linked list TYPE deleteHead(LinkedList *ll){ Node *first=(Node*)ll->head; if (first){ TYPE value=first->data; ll->head=(Node *)first->next; free(first); if (!ll->head) ll->tail=NULL; return value; } return -1 ;/* ??? this is BAD */ int main() { LinkedList ll;initLinkedList(&ll); printLinkedList(ll.head); addTail(&ll,1);addHead(&ll,5);addHead(&ll,6);addTail(&ll,7); printf("deleted %d\n",deleteHead(&ll)); return 0; [] [6 5 1 7 ] deleted 6 [5 1 7 ]

Delete – the Tail Item List before deletion: How to get the before last? List after deletion of the tail item: data data data data data tail_ptr head_ptr data data data data data tail_ptr head_ptr New value of tail_ptr = link-value of the 3rd from last item New link-value of new last item = NULL.

size() and isEmpty() We need to scan the items in the list from the head_ptr to the last item marked by its link-value being NULL Count the number of items in the scan, and return the count. This is the size(). Alternatively, keep a counter of the number of item, which gets updated after each insert/delete. The function size( ) returns that counter If head_ptr is NULL, isEmpty() returns true; else, it returns false.

Searching for an Item Suppose you want to find the item whose data value is A You have to search sequentially starting from the head item rightward until the first item whose data member is equal to A is found. At each item searched, a comparison between the data member and A is performed.

Recursive versus Iterative void printLinkedList(Node *n){ printf("["); while (n) {printf("%d ",n->data);n=(Node *)n->next;} printf("]\n"); } void printLinkedListRecursive(Node *n){ if (!n) printf("\n"); else {printf("%d ",n->data); printLinkedListRecursive(n->next); Node * search(Node *n,TYPE value) { if (!n) return NULL; if (n->data==value) return n; else return search(n->next,value);

Back To Queues, Linked list Implementation struct node { TYPE data; struct node *link; }; struct Queue { struct node *front, *rear; void initQueue(struct Queue *q) {q->front=q->rear=NULL;} //struct node *front, *rear; void enqueue(struct Queue *,int); TYPE dequeue(struct Queue *); int isEmpty(struct Queue*); int main() { struct Queue q; initQueue(&q); int i;for (i=0;i<100;i++) enqueue(&q,i);//No isfull() while (!isEmpty(&q)) printf("[%d]",dequeue(&q)); return 0; } [0][1][2][3][4]...[98][99]

Back To Queues, Linked list Implementation void enqueue (struct Queue *q,int y) { struct node *ptr; ptr=malloc(sizeof(struct node)); ptr->data=y; ptr->link=NULL; if(q->front ==NULL) q->front = q->rear= ptr; else q->rear->link=ptr; q->rear=ptr; } TYPE dequeue (struct Queue *q) TYPE num; if(q->front==NULL) return 0; num=q->front->data; q->front = q->front->link; return num; int isEmpty(struct Queue *q){ return q->front==NULL?1:0;

Arrays: pros and cons + Fast element access. -- Impossible to resize. Many applications require resizing! Required size not always immediately available.

Singly Linked Lists A singly linked list is a concrete data structure consisting of a sequence of nodes Each node stores element link to the next node next node elem  A B C D

OO Node Class public class Node { // Instance variables: private Object element; private Node next; /** Creates a node with null references to its element and next node. */ public Node() { this(null, null); } /** Creates a node with the given element and next node. */ public Node(Object e, Node n) { element = e; next = n; // Accessor methods: public Object getElement() { return element; public Node getNext() { return next; // Modifier methods: public void setElement(Object newElem) { element = newElem; } public void setNext(Node newNext) { next = newNext;

Singly linked list public class SLinkedList { protected Node head; // head node of the list /** Default constructor that creates an empty list */ public SLinkedList() { head = null; } // ... update and search methods would go here ...

Inserting at the Head Allocate a new node Insert new element Make new node point to old head Update head to point to new node

Removing at the Head Update head to point to next node in the list Allow garbage collector to reclaim the former first node

Singly linked list with ‘tail’ sentinel public class SLinkedListWithTail { protected Node head; // head node of the list protected Node tail; // tail node of the list /** Default constructor that creates an empty list */ public SLinkedListWithTail() { head = null; tail = null; } // ... update and search methods would go here ...

Inserting at the Tail Allocate a new node Insert new element Have new node point to null Have old last node point to new node Update tail to point to new node

Removing at the Tail Removing at the tail of a singly linked list cannot be efficient! There is no constant-time way to update the tail to point to the previous node

A B C D Doubly Linked List A doubly linked list is often more convenient! Nodes store: element link to the previous node link to the next node Special trailer and header nodes prev next elem node trailer header nodes/positions A B C D elements Linked Lists

Insertion p A B C p q A C p q A B X C We visualize operation insertAfter(p, X), which returns position q p A B C p q A C p q A B X C Linked Lists

Insertion p A B C p q A B C X p q A B X C We visualize operation insertAfter(p, X), which returns position q p A B C p q A B C 1-q=new Node(x) X p q A B X C Linked Lists

Insertion p A B C p q A B C X p q A B X C We visualize operation insertAfter(p, X), which returns position q p A B C 2-q->next=p->next p q A B C X p q A B X C Linked Lists

Insertion p A B C p q A B C X p q A B X C We visualize operation insertAfter(p, X), which returns position q p A B C 4-q->prev=p->next->prev p q A B C X p q A B X C Linked Lists

Insertion p A B C p q A B C X p q A B X C We visualize operation insertAfter(p, X), which returns position q p A B C 5-p->next=q->next->prev=q p q A B C X p q A B X C Linked Lists

Insertion Algorithm Algorithm insertAfter(p,e): Create a new node v v.setElement(e) v.setPrev(p) {link v to its predecessor} v.setNext(p.getNext()) {link v to its successor} (p.getNext()).setPrev(v) {link p’s old successor to v} p.setNext(v) {link p to its new successor, v} return v {the position for the element e}

Deletion We visualize remove(p), where p == last() A B C D p A B C p D

Deletion Algorithm Algorithm remove(p): return t t = p.element {a temporary variable to hold the return value} (p.getPrev()).setNext(p.getNext()) {linking out p} (p.getNext()).setPrev(p.getPrev()) p.setPrev(null) {invalidating the position p} p.setNext(null) return t

Worst-cast running time In a doubly linked list + insertion at head or tail is in O(1) + deletion at either end is on O(1) -- element access is still in O(n)

Thanks