Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures Linked list.

Similar presentations


Presentation on theme: "Data Structures Linked list."— Presentation transcript:

1 Data Structures Linked list

2 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;

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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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( )

22 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

23 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

24 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;}

25 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!

26 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; } [] [ ]

27 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

28 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; [] [ ] deleted 6 [5 1 7 ]

29 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.

30 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.

31 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.

32 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);

33 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]

34 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;

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

36 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

37 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;

38 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 ...

39 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

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

41 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 ...

42 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

43 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

44 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

45 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

46 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

47 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

48 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

49 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

50 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}

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

52 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

53 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)

54 Thanks


Download ppt "Data Structures Linked list."

Similar presentations


Ads by Google