You are on page 1of 215

Resmi N.G. References: Data Structures and Algorithms: Alfred V. Aho, John E. Hopcroft, Jeffrey D.

Ullman A Practical Approach to Data Structures and Algorithms: Sanjay Pahuja

Module 2
Module II (18 hours) Linear Data Structures - Stacks Queues -Lists Dequeues - Linked List - singly, doubly linked and circular lists - Application of linked lists - Polynomial Manipulation - Stack & Queue implementation using Array & Linked List - Typical problems - Conversion of infix to postfix - Evaluation of postfix expression priority queues

10/25/2012

CS 09 303 Data Structures - Module 2

LIST
Flexible data structure: grows and shrinks on demand. Elements can be accessed, inserted, or deleted at any position within

a list.
Lists can be concatenated or split into sub-lists. Mathematically, a list is a sequence of zero or more elements of a

given type. Represented by a comma separated sequence of elements a1,a2,an where n>=0 and each ai is of a given type.
n is the length of the list.
10/25/2012 CS 09 303 Data Structures - Module 2 3

Features Of List
Can be linearly ordered according to their position on the list. Concatenation and splitting possible Main application areas are: => Information retrieval => Programming language translation => Programming language simulation

10/25/2012

CS 09 303 Data Structures - Module 2

LIST OPERATIONS
INSERT(x, p,L) : Inserts x at position p in list L. Move elements at p and following positions to next higher positions. Insert x at position p in list L. If L is a1, a2, , an, then L becomes a1, a2, , ap-1, x, ap, , an . If p is END (L), then L becomes a1, a2, , an, x.

10/25/2012

CS 09 303 Data Structures - Module 2

END(L) : returns the last position of list L LOCATE(x, L) : returns the position of x on list L.
If x appears more than once, it returns the position of first occurrence of x. If x does not appear at all, then it returns END(L).

RETRIEVE(p,L) : returns element at position p on list L.


Result is undefined if p = END (L) or if L has no position p.

10/25/2012

CS 09 303 Data Structures - Module 2

DELETE(p, L) : deletes the element at position p of list L.


If list is a1,a2, , an, then the list L becomes a1, a2, ap-1, ap+1, ,an.

NEXT(p, L): returns position following p on list L. PREVIOUS(p, L):returns position preceding p on list L. MAKENULL(L) : Makes the list L empty and returns the position END(L). FIRST(L) : returns first position on list L. PRINTLIST(L) :prints elements of L in order of occurrence.

10/25/2012

CS 09 303 Data Structures - Module 2

Implementation Of List
2 Ways Array Implementation Pointer Implementation(Linked List representation)

10/25/2012

CS 09 303 Data Structures - Module 2

Array Implementation Of List


Elements are stored in contiguous cells of an array. Easily traversed Elements can be appended readily to the end of the list. Definition of LIST: is a record that contains 2 fields:
an array of elements with maximum required length an integer last : indicating position of the last list element in the array.

10/25/2012

CS 09 303 Data Structures - Module 2

Array Implementation Of List (Definition)


const MAXLEN = 100; type LIST = record elements:array[1..MAXLEN] of elementtype; last :integer; end;

position = integer;
10/25/2012 CS 09 303 Data Structures - Module 2 10

END(L) Algorithm
function END (var L: List) : position; begin return (L.last + 1) {gives total no. of elements in the list} end; {END}
0 50 1 107 2 15 3 201 L.last

10/25/2012

CS 09 303 Data Structures - Module 2

11

INSERTION Algorithm
procedure INSERT(x : elementtype; p : position; var L: LIST) {INSERT places x at position p in list L} var q:position; begin if L.last >= MAXLEN then error (list is full) else if (p > L.last + 1 ) or ( p < 1) then error(position does not exist) else begin for q := L.last downto p do {shift elements at p, p+1 down by one position} L.elements[q+1] := L.elements[q]; L.last := L.last+1; L.elements[p] := x; end end;{INSERT}
10/25/2012 CS 09 303 Data Structures - Module 2 12

Insertion
Insert (47, 0, L)
0 1 2 3

L.last := L.last + 1 = -1 + 1 = 0 L.elements[0] := 47;


47 p
10/25/2012

L.last
CS 09 303 Data Structures - Module 2 13

Insert (59, 1, L)
0 47 L.last p 1 2 3

L.last := L.last + 1 = 0 + 1 = 1 L.elements[1] := 59;


47 p 59 L.last

10/25/2012

CS 09 303 Data Structures - Module 2

14

Insert (65, 2, L)
0 47 1 59 L.last p 2 3

L.last := L.last + 1 = 1 + 1 = 2 L.elements[2] := 65;


47 59 p 65 L.last

10/25/2012

CS 09 303 Data Structures - Module 2

15

Insert (53, 1, L)
0 47 1 59 p q 2 65 L.last 3

Shift elements down to insert at position 1. Start with q = L.last. L.elements[q+1] := L.elements[q] { Move element at position 2 to position 3. L.elements[2+1] = L.elements[2] L.elements[3] = L.elements[2] }
47 59 p
10/25/2012 CS 09 303 Data Structures - Module 2

65 q L.last q+1
16

Decrement q until q = p. So, q = 1.


0 47 1 59 p q L.last 2 3 65

L.elements[q+1] := L.elements[q] { Move element at position 1 to position 2. L.elements[1+1] = L.elements[1] L.elements[2] = L.elements[1] }
47 p q
10/25/2012

59 q+1 L.last

65

CS 09 303 Data Structures - Module 2

17

Now, q = p = 1. So, insert element at position 1.


0 47 p q 1 2 59 L.last 3 65

L.last := L.last + 1 = 2+1 = 3; L.elements[p] := L.elements[1] = 53;

47

53 p q

59

65 L.last
18

10/25/2012

CS 09 303 Data Structures - Module 2

DELETION Algorithm
procedure DELETE (p:position; var L : LIST) {DELETE removes the element at position p of list L} var q:position; begin if ( p > L.last ) or ( p < 1) then error(position does not exist) else begin L.last := L.last-1; for q := p to L.last do {shift elements at p+1, p+2, up one position} L.elements[q] := L.elements[q+1]; end end;{DELETE}
10/25/2012 CS 09 303 Data Structures - Module 2 19

Deletion
Delete (1, L)
0 47 1 53 p 2 59 3 65

L.last

L.last := L.last - 1 = 3-1= 2

47

53 p

59 L.last

65

10/25/2012

CS 09 303 Data Structures - Module 2

20

To delete element at 1, shift elements at 2 and 3 up by one position. Start with q = p. ie. q = 1.
0 47 1 53 p q q+1 2 59 L.last 3 65

Move element at location q+1 = 2 to location q = 1. L.elements[q] := L.elements[q+1];

47

59 p q q+1 L.last

65

10/25/2012

CS 09 303 Data Structures - Module 2

21

Increment q until q = L.last = 2. So, q = q + 1 = 2.


0 47 1 59 p q 2 59 L.last 3 65 q+1

Move element at location q+1 = 3 to location q = 2. L.elements[q] := L.elements[q+1];


47 59 p
10/25/2012

65 q L.last
22

CS 09 303 Data Structures - Module 2

LOCATE Algorithm
function LOCATE( x:elementtype; var L:LIST) : position; {LOCATE returns position of x on list L} var q:position; begin for q:=1 to L.last do if L.elements[q] = x then return(q); else return( L.last + 1 ) {if not found} end;{LOCATE}

10/25/2012

CS 09 303 Data Structures - Module 2

23

Removing Duplicates in a LIST


Procedure PURGE (Var L:List); {PURGE removes duplicate elements from list L} Var p,q : position; {p will be the current position in L, and q will move ahead to find equal elements} Begin (1) p := FIRST(L); (2) While p <> END(L) do begin (3) q := NEXT(p, L); (4) while q <> END(L) do (5) if same (RETRIEVE (p, L), RETRIEVE (q, L ) then (6) DELETE(q,L); (7) else (8) q:=NEXT(q,L); (9) p:=NEXT(p,L) (10) End; End; {PURGE}
10/25/2012 CS 09 303 Data Structures - Module 2 24

Pointer Implementation Of List: (LINKED LIST)


Use of special data structure - Linked List Singly-linked cells which use pointers to link successive list

elements are used here. Does not require contiguous memory for storage. Allocates memory dynamically Linked List is made up of cells, and each cell contains: Element of the list Pointer to next cell on the list If the list is a1,a2,an, the cell holding ai has a pointer to the cell holding ai+1, for i = 1, 2, n-1. Header holds no element but points to cell holding a1. The cell holding an has a nil pointer.
CS 09 303 Data Structures - Module 2 25

10/25/2012

10/25/2012

CS 09 303 Data Structures - Module 2

26

Classification Of Linked Lists


Linear or singly linked list Doubly Linked List Circular Linked List Circular Doubly linked List

10/25/2012

CS 09 303 Data Structures - Module 2

27

Linear Singly Linked List


Definition type celltype = record element:elementtype; next: celltype; end; LIST= celltype; position = celltype;

10/25/2012

CS 09 303 Data Structures - Module 2

28

Operations Of Singly Linked List


END(L) Algorithm Function END(var L : List) : position; {END returns a pointer to the last cell of L} Var q:position; begin (1) q:=L; (2) While q .next <> nil do (3) q:= q .next; (4) return(q) end; {END}
10/25/2012 CS 09 303 Data Structures - Module 2 29

Operations Of Singly Linked List INSERTION


Steps involved are : Find the correct location Insert the element

10/25/2012

CS 09 303 Data Structures - Module 2

30

Finding the Correct Location


Three possible positions: The front The end Somewhere in between the existing cells

10/25/2012

CS 09 303 Data Structures - Module 2

31

Inserting to the Front


head 93 head 48 17 142

There is no work to find the location. Insertion at the beginning of the list

No Worries!
10/25/2012 CS 09 303 Data Structures - Module 2 32

Inserting to the End


head 48 17 142 93 //

//

Find the end of the list (when at NIL)

No Worries!
10/25/2012 CS 09 303 Data Structures - Module 2 33

Inserting to the Middle


head 17 48 142 93 142 //

//

Used when the order is important.

10/25/2012

CS 09 303 Data Structures - Module 2

34

Operations Of Singly Linked List(contd..)


INSERTION Algorithm Procedure INSERT(var x : elementtype, p : position); {Inserts a cell with element x after position p} Var temp : position; Begin (1) temp := p . next; (2) New(p .next); (3) p .next .element := x; (4) p .next .next := temp; End;{INSERT}

10/25/2012

CS 09 303 Data Structures - Module 2

35

Explanation
(1) temp := p . next; {address of the cell next to p is stored in temp}

head

4 p

6 Temp

10/25/2012

CS 09 303 Data Structures - Module 2

36

(2) New(p .next); {A new cell is created and its address is assigned to p .next}
head

4 p

6 temp p . next = address of new cell

p . next
10/25/2012 CS 09 303 Data Structures - Module 2 37

(3) p .next .element := x; {Element at p .next is assigned as x}

head

4 p

6 temp p . next . element = 5 5 p . next

10/25/2012

CS 09 303 Data Structures - Module 2

38

(3) p .next . next := temp; {Next of p .next is assigned as temp}

head

4 p temp

p . next . next = temp 5 p . next


10/25/2012 CS 09 303 Data Structures - Module 2 39

head

10/25/2012

CS 09 303 Data Structures - Module 2

40

Operations Of Singly Linked List(contd..)


DELETION Algorithm Deletes the element after position p. Procedure DELETE( var p:position); Begin p .next := p .next .next; End;{DELETE}

10/25/2012

CS 09 303 Data Structures - Module 2

41

Deletion at the front


head
6 4 17 42

Head has the address of first node

10/25/2012

CS 09 303 Data Structures - Module 2

42

Deletion at the front


head
6 4 17 42

Head is made to point to the next cell.

10/25/2012

CS 09 303 Data Structures - Module 2

43

Deletion from in between the cells


head
4 17 42

10/25/2012

CS 09 303 Data Structures - Module 2

44

Deletion from in between the cells


head
4 17 42

10/25/2012

CS 09 303 Data Structures - Module 2

45

Deletion from in between the cells


p p . next = p . next . next p . next p . next . next

10/25/2012

CS 09 303 Data Structures - Module 2

46

Operations Of Singly Linked List(contd..)


LOCATE Algorithm Function LOCATE( var x : elementtype; var L:LIST):position; Var p : position; Begin p := L; while p . next <> nil do if p . next . element = x then return (p); else p := p . next ; return (p) {if not found} End;{LOCATE}

10/25/2012

CS 09 303 Data Structures - Module 2

47

Deleting a particular element


head

17

42

Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

48

head p 6

17

42

Start searching from the beginning of the list L. Initially, p = L; Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

49

head p 6

17

42

Check if p.next.element = 4. NO. So, move onto next cell. p = p.next Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

50

head

17

42

p Check if p.next.element = 4. YES. So, perform the operation p.next = p.next.next Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

51

head

17

42

p .next = p.next.next

Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

52

head

17

42

Target = 4

10/25/2012

CS 09 303 Data Structures - Module 2

53

head

17

42

10/25/2012

CS 09 303 Data Structures - Module 2

54

Operations Of Singly Linked List(contd..)


MAKENULL Algorithm Function MAKENULL(Var L:LIST):position; Begin new(L); L .next := nil; return(L); End; {MAKENULL}

Creates an empty list L


10/25/2012 CS 09 303 Data Structures - Module 2 55

Doubly Linked List


Each cell has a pointer to the next and previous cells on the list. Given an element, it is easy to determine the preceding and following elements quickly. Can be used to traverse a list in both forward and backward directions.

10/25/2012

CS 09 303 Data Structures - Module 2

56

10/25/2012

CS 09 303 Data Structures - Module 2

57

10/25/2012

CS 09 303 Data Structures - Module 2

58

Doubly Linked List


Definition Type celltype = record element : elementtype; next , previous : celltype; End; position = celltype; newnode = celltype;
10/25/2012 CS 09 303 Data Structures - Module 2 59

Doubly Linked List


INSERTION ALGORITHM Procedure INSERT( var element:elementtype; var pos:position) Var Temp : position; Begin Temp := L; i : =1; while (i < pos and Temp < > NIL ) begin Temp : = Temp . Next; i : = i + 1; End;
10/25/2012 CS 09 303 Data Structures - Module 2 60

If Temp < > NIL and i = pos then begin New( newNode); newNode .element : = element; newNode .next : = Temp .next; newNode . previous : = Temp; Temp .next . previous : = newNode; Temp . next := newNode; end { if } Else begin error ( position not found ) end; { INSERT}
10/25/2012 CS 09 303 Data Structures - Module 2 61

Explanation
temp := L; i : =1; temp 5 15 20 head

Check if i<pos, and temp<>NIL. i=1, pos = 2 and temp<>NIL. So, move forward. temp = temp.next i = i+1
10/25/2012 CS 09 303 Data Structures - Module 2 62

head

5 temp

15

20

Check if i<pos, and temp<>NIL. i=2, pos = 2 and temp<>NIL. So, do insertion.

10/25/2012

CS 09 303 Data Structures - Module 2

63

If Temp < > NIL and i = pos then begin new( newNode); {Creates a new node in memory and assigns its address to newnode.}

newNode .element : = element; {Inserts element at newnode.}


10 head

5 temp

15

20

10/25/2012

CS 09 303 Data Structures - Module 2

64

head

5 temp

15

20

10

newNode .next : = temp .next;

10/25/2012

CS 09 303 Data Structures - Module 2

65

head

5 temp

15

20

10

newNode . previous : = temp;

10/25/2012

CS 09 303 Data Structures - Module 2

66

head temp . next

5 temp

15

20

temp .next . previous : = newNode;

10

10/25/2012

CS 09 303 Data Structures - Module 2

67

head

5 temp

15

20

temp .next : = newNode;


10

10/25/2012

CS 09 303 Data Structures - Module 2

68

head

10

15

20

10/25/2012

CS 09 303 Data Structures - Module 2

69

Deletion in Doubly Linked List

10/25/2012

CS 09 303 Data Structures - Module 2

70

DELETION ALGORITHM Procedure DELETE ( Var p : position); Begin if p . Previous < > nil then { deleted cell not the first } p . Previous . Next : = p . Next; if p . Next < > nil then { deleted cell not the last } p . Next . Previous : = p . Previous End { DELETE}

10/25/2012

CS 09 303 Data Structures - Module 2

71

p . previous . next = p . next;

p. next . previous = p . previous ;

10/25/2012

CS 09 303 Data Structures - Module 2

72

STACK
An Abstract Data Type Special List : insertions & deletions at one

end(top)
Also called LIFO(Last In First Out) list.
10/25/2012 CS 09 303 Data Structures - Module 2 73

10/25/2012

CS 09 303 Data Structures - Module 2

74

10/25/2012

CS 09 303 Data Structures - Module 2

75

Operations performed on stack


MAKENULL(S) : Make stack S an empty stack. TOP(S) : Return the top element of stack S. POP(S) : Delete the top element from the stack. {check for stack empty condition} PUSH(x,S) : Insert the element x at the top of stack S. { Stack overflow condition should be checked} EMPTY(S) : Returns true if S is an empty stack.
10/25/2012 CS 09 303 Data Structures - Module 2 76

Stack Implementation
Static implementation(Using arrays) Dynamic implementation(Using pointers)

10/25/2012

CS 09 303 Data Structures - Module 2

77

Definition of Array-Based Stack


type STACK = record top : integer; elements : array[1..MAXLENGTH] of elementtype; end;

10/25/2012

CS 09 303 Data Structures - Module 2

78

Array Implementation
Procedure PUSH( var x:elementtype; Var s:STACK); Begin If s.top = MAXLENGTH -1 then error(stack is full) Else begin s.top:=s.top+1; s.elements[s.top]:=x; End; End;{PUSH}
10/25/2012 CS 09 303 Data Structures - Module 2 79

Initial stack
3 2 1 0
Top = -1

10/25/2012

CS 09 303 Data Structures - Module 2

80

Push (12, S)
s.top:=s.top+1 = -1 + 1 = 0; s.elements[s.top]:= s.elements[0] = 12; 3 2 1 0 12
Top = 0

10/25/2012

CS 09 303 Data Structures - Module 2

81

Push (34, S)
s.top:=s.top+1 = 0 + 1 = 1; s.elements[s.top]:= s.elements[1] = 34; 3 2 1 0 34 12
Top = 1

10/25/2012

CS 09 303 Data Structures - Module 2

82

Push (47, S)
s.top:=s.top+1 = 1 + 1 = 2; s.elements[s.top]:= s.elements[2] = 47; 3 2 1 0 47 34 12
Top = 2

10/25/2012

CS 09 303 Data Structures - Module 2

83

Push (53, S)
s.top:=s.top+1 = 2 + 1 = 2; s.elements[s.top]:= s.elements[3] = 53; 3 2 1 0 53 47 34 12
Top = 3

Stack full (Top = max-1);

10/25/2012

CS 09 303 Data Structures - Module 2

84

Procedure POP( Var s:STACK); begin if EMPTY(s) then error(stack is empty) else s.top := s.top-1; end;{POP}

10/25/2012

CS 09 303 Data Structures - Module 2

85

Procedure MAKENULL( Var s:STACK); Begin s.top:= -1; End;{MAKENULL}

10/25/2012

CS 09 303 Data Structures - Module 2

86

Function EMPTY( Var s:STACK):boolean; begin If s.top<0 then return(true); else return(false); end;{EMPTY}

10/25/2012

CS 09 303 Data Structures - Module 2

87

Function TOP ( Var s:STACK):elementtype; begin If EMPTY(s) then error(stack is empty) else return(s.elements[s.top]); end;{TOP}

10/25/2012

CS 09 303 Data Structures - Module 2

88

Applications of stack
Explicit and implicit recursive calls Conversion of Infix to postfix Postfix expression evaluation Conversion of infix to prefix Prefix expression evaluation Parenthesis checker

10/25/2012

CS 09 303 Data Structures - Module 2

89

Applications of stack
Expression : operands together with operator Infix notation(A+B) Prefix notation( +AB) Postfix notation( AB+) Operator precedence ^ (Exponential ) .Highest *, /(mul, div) Next highest +, - (add,sub) Lowest

10/25/2012

CS 09 303 Data Structures - Module 2

90

Applications of stack
Conversion from infix to postfix Rules 1. Parenthesize the expression starting from left to right 2. The operands associated with the operator having higher precedence will be parenthesized first. 3. The sub expression which has been converted to postfix is to be treated as single operand. 4. Once the expression is converted to postfix form, remove the parenthesis

10/25/2012

CS 09 303 Data Structures - Module 2

91

Infix to postfix conversion algorithm


P =>postfix expression Q =>infix expression (1) Push ( onto stack and add ) to the end of Q. (2) Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the stack is empty. (3) If an operand is encountered, add it to P. (4) If an operator # is encountered, then (a) Repeatedly pop from stack and add to P each operator (on the top of stack) which has equal or higher precedence than #.
10/25/2012 CS 09 303 Data Structures - Module 2 92

(b) Add # to stack. 5. If a left parenthesis is encountered, push it onto the stack. 6. If a right parenthesis is encountered then (a) Repeatedly pop from stack and add to P, until a left parenthesis is encountered. (b) Remove the left parenthesis. [ do not add the left parenthesis to P]. 7. Exit #
10/25/2012

Symbolizes any operator in Q


CS 09 303 Data Structures - Module 2 93

10/25/2012

CS 09 303 Data Structures - Module 2

94

10/25/2012

CS 09 303 Data Structures - Module 2

95

Evaluating Postfix expression


(1) Add a right parenthesis ) at the end of P[this acts as a

sentinel]. (2) Scan P from left to right and repeat steps 3 and 4 for each element of P until the sentinel ) is encountered. (3) If an operand is encountered, put it on STACK. (4) If an operator # is encountered, then (a) Remove the two top elements of STACK ,where A is the top element and B is the next-to-top element. (b) Evaluate B # A. (c) Place the result onto STACK. 5) RESULT equal to the top element on stack. 6) Exit
10/25/2012 CS 09 303 Data Structures - Module 2 96

Evaluate 45+72-*

10/25/2012

CS 09 303 Data Structures - Module 2

97

Evaluate 59+2*65*+

10/25/2012

CS 09 303 Data Structures - Module 2

98

Infix to prefix conversion algorithm


I => infix expression O => output expression P => prefix expression
(1) Push ) onto stack and add ( to the beginning of I. (2) Scan I from right to left and repeat steps 3 to 6 for each

element of I until the stack is empty. (3) If an operand is encountered, add it to O. (4) If an operator # is encountered, then (a) Repeatedly pop from stack and add to O each operator (on the top of stack) which has higher precedence than #.
10/25/2012 CS 09 303 Data Structures - Module 2 99

(b) Add # to stack. 5. If a right parenthesis is encountered, push it onto the stack. 6. If a left parenthesis is encountered then (a) Repeatedly pop from stack and add to O, until a right parenthesis is encountered. (b) Remove the right parenthesis. [ do not add the right parenthesis to O]. 7. Reverse O to get the prefix expression P. 8. Exit #
10/25/2012

Symbolizes any operator in I.


CS 09 303 Data Structures - Module 2 100

Convert (A*B-F*H)^D
Symbol Scanned D ^ ) H * F B * A ( ( Operator Stack ) )^ )^) )^) )^)* )^)* )^))^))^)-* )^)-* )^ (Empty) Output Expression D D D DH DH DHF DHF* DHF*B DHF*B DHF*BA DHF*BA*DHF*BA*-^

Result: ^-*AB*FHD
10/25/2012 CS 09 303 Data Structures - Module 2 101

Home Work
Convert to prefix: A+ [ B+C - D+E] * F / G +A/*+-+BCDEFG (ab)/c*(d + e f / g) */-abc-+de/fg

10/25/2012

CS 09 303 Data Structures - Module 2

102

Convert (ab)/c*(d + e f / g)

10/25/2012

CS 09 303 Data Structures - Module 2

*/-abc-+de/fg 103

Evaluating Prefix expression


(1) Add a left parenthesis ( at the beginning of P[this acts

as a sentinel]. (2) Scan P from right to left and repeat steps 3 and 4 for each element of P until the sentinel ( is encountered. (3) If an operand is encountered, push it onto STACK. (4) If an operator # is encountered, then (a) Remove the two top elements of STACK ,where A is the top element and B is the next-to-top element. (b) Evaluate A # B. (c) Place the result onto STACK. 5) RESULT equal to the top element on stack. 6) Exit
10/25/2012 CS 09 303 Data Structures - Module 2 104

Evaluate *+45-72

10/25/2012

CS 09 303 Data Structures - Module 2

105

Parenthesis Checker
To check whether a mathematical expression is properly parenthesized or not. 3 sets of grouping symbols The standard parenthesis () The braces { } The brackets []

10/25/2012

CS 09 303 Data Structures - Module 2

106

Algorithm for Parenthesis Checker


Make an empty stack. Read symbols until end of file is reached. If the symbol is an opening symbol, push it onto the stack. If it is a closing symbol, do the following: If the stack is empty, then report an error. Otherwise, pop the stack. If the symbol popped does not match the closing symbol, then report an error. At the end of the file, if the stack is not empty, then report an error.

10/25/2012

CS 09 303 Data Structures - Module 2

107

Algorithm for parenthesis checker


Begin read expression for each character c in expression if(current symbol or character is a left symbol) then push the character onto stack. else if (current symbol is a right symbol ) then if(stack is empty) then print (Error no matching open symbol) exit

10/25/2012

CS 09 303 Data Structures - Module 2

108

else pop a symbol s from the stack if (s does not correspond to c ) then print error incorrect nesting of symbols exit end {if} end {if} end {if} end {for}

10/25/2012 CS 09 303 Data Structures - Module 2 109

if (stack is not empty ) then print error missing closing symbol else print input expression is OK end {if} END

10/25/2012

CS 09 303 Data Structures - Module 2

110

Self-Study (Homework)
Stack using Linked List Write algorithms to:
Push an element onto stack Pop an element Create an empty stack Check if stack is empty Return the top element from the stack

10/25/2012

CS 09 303 Data Structures - Module 2

111

QUEUES
Abstract data type which is special kind of List where items are

inserted at one end (rear) and deleted from the other end (front).
Insertion :Rear Deletion :Front Also called FIFO(First In First Out) list.
10/25/2012 CS 09 303 Data Structures - Module 2 112

front

rear

10/25/2012

CS 09 303 Data Structures - Module 2

113

QUEUE OPERATIONS
MAKENULL(Q) : makes queue Q an empty list FRONT(Q) : returns first element of Q ENQUEUE(x, Q) : inserts element x at end of Q DEQUEUE(Q) : deletes first element of Q EMPTY(Q) : returns true if Q is an empty queue.

10/25/2012

CS 09 303 Data Structures - Module 2

114

10/25/2012

CS 09 303 Data Structures - Module 2

115

10/25/2012

CS 09 303 Data Structures - Module 2

116

IMPLEMENTATION OF QUEUE
Using Arrays (Static implementation) Using Pointers (Dynamic implementation)

10/25/2012

CS 09 303 Data Structures - Module 2

117

Array Implementation
Type QUEUE = record elements : array[1..MAXLENGTH] of elementtype; front, rear: integer; end;

10/25/2012

CS 09 303 Data Structures - Module 2

118

Queue operations using Arrays


Insertion Operation procedure ENQUEUE( Var data:integer, Var Q: QUEUE) begin read(data); If Q.rear >= SIZE then begin error(Queue Overflow); exit(); end else Q.rear := Q.rear+1; end; Q.elements[Q.rear] := data; end;{ENQUEUE}
(1)

10/25/2012

CS 09 303 Data Structures - Module 2

119

(1)Empty Queue
Rear := -1 Front := -1 0 rear front 1 2 3

(2)ENQUEUE(10,Q)
Front := 0 Rear := rear + 1 = 0 Q[Rear] := Q[0] = 10

10
0 rear 1 front 2 3

(3) ENQUEUE(3,Q) Rear = rear + 1 = 0 + 1 = 1 Q[Rear] := Q[1] = 3

10
0 front 1

3
2 3 rear
120

10/25/2012

CS 09 303 Data Structures - Module 2

(4)ENQUEUE(17,Q)
Rear := rear + 1 = 1 + 1 =2 Q[Rear] := Q[2] = 17

10
0 1 front

17
2 rear 3

(5)ENQUEUE(29,Q)
Rear := rear + 1 = 2+1 = 3 Q[Rear] := Q[3] = 29

10
0 front 1

17
2

29
3 rear

Queue Full (rear = max - 1)

10/25/2012

CS 09 303 Data Structures - Module 2

121

Deletion Operation Function DEQUEUE(Var Q: QUEUE) : elementtype; Begin if Q.rear < Q.front then begin Q.front:=0; Q.rear:= -1; error(Queue is empty); exit(); end else begin dequeue := Q.elements[Q.front]; Q.front:= Q.front+1; end; end;{DEQUEUE}
(2)

10/25/2012

CS 09 303 Data Structures - Module 2

122

(1)DEQUEUE(Q)
data := Q[front] = Q[0] =10 front := front + 1 = 0 + 1 = 1 0 1 front

17
2

29
3 rear

(1)DEQUEUE(Q)
data := Q[front] = Q[1] = 3 front := front + 1 = 1 + 1 = 2

17
0 1 front 2

29
3 rear

(2)DEQUEUE(Q)
data := Q[front] = Q[2] = 17 front := front + 1 = 2 + 1 = 3

29
0 1 2 3 front rear

10/25/2012

CS 09 303 Data Structures - Module 2

123

(4)DEQUEUE(Q)
data := Q[front] = Q[3] = 29 front := front + 1 = 3 + 1 = 4 0 1 2 3 rear front = 4

Queue empty (rear < front)

10/25/2012

CS 09 303 Data Structures - Module 2

124

Queue operations using Pointers


(1) Definition of Queue

type celltype = record element: elementtype; next : celltype; end; type QUEUE = record front, rear : celltype; end;
10/25/2012 CS 09 303 Data Structures - Module 2 125

(1) To Make a NULL QUEUE procedure MAKENULL(Var Q:QUEUE); begin new(Q.front);{create header cell } Q.front .next := nil; Q.rear := Q.front; {header is both first &last cell } end;{MAKENULL}

10/25/2012

CS 09 303 Data Structures - Module 2

126

(2) Check if QUEUE is empty function EMPTY(Var Q:QUEUE): boolean; begin if Q.front = Q.rear then return(true); else return(false); end;{EMPTY}

10/25/2012

CS 09 303 Data Structures - Module 2

127

(3) Returning first element from a queue

function FRONT(Var Q:QUEUE):elementtype begin If EMPTY(Q) then error(Queue is empty); else return(Q . front . next . element) end;{FRONT}

10/25/2012

CS 09 303 Data Structures - Module 2

128

(4) Insertion into a queue

Procedure ENQUEUE( var x:elementtype;Var Q:Queue); begin new(Q.rear . next); {add new cell to rear of queue} Q.rear := Q.rear . next; Q. rear .element := x; Q.rear .next:=nil; end; {ENQUEUE}

10/25/2012

CS 09 303 Data Structures - Module 2

129

(5) Deletion from a queue

Function DEQUEUE(Var Q:Queue): elementtype; Begin if EMPTY(Q) then error(queue is empty) else begin dequeue := Q.front .element; Q.front := Q.front .next; end; end; {DEQUEUE}
10/25/2012 CS 09 303 Data Structures - Module 2 130

Different Types Of Queue


Circular Queue Double ended Queue Priority Queue

10/25/2012

CS 09 303 Data Structures - Module 2

131

Circular Queue

10/25/2012

CS 09 303 Data Structures - Module 2

132

CIRCULAR QUEUE
Q[1] following Q[n] Conditions of circular Queue: Insertion Condition
rear = (rear+1) % SIZE

Deletion Condition
front = (front + 1) % SIZE

QUEUE FULL
rear = front
10/25/2012 CS 09 303 Data Structures - Module 2 133

Algorithms of Circular Queue


Insertion Procedure ENQUEUE(Var data:integer,Var Q : QUEUE); Begin if Q.front = ((Q.rear + 1) % SIZE) then begin error(Queue Full) exit(); end else begin Q.rear := (Q.rear + 1) % SIZE; end; if Q.front = -1 then begin Q.front := 0; Q.rear := 0; end; read(data); Q.elements[Q.rear] := data; end;{ENQUEUE}
10/25/2012 CS 09 303 Data Structures - Module 2 134

Queue is empty (front = rear = -1)


0 1

Rear=-1 Front=-1

10/25/2012

CS 09 303 Data Structures - Module 2

135

Enqueue (14, Q) Rear := (rear + 1) % SIZE = (-1 + 1) % 4 = 0 % 4 = 0 Q.elements[0] := 14;


Rear = 0

0
Front = 0

1 14

3
10/25/2012 CS 09 303 Data Structures - Module 2

2
136

Enqueue (42, Q) Rear := (rear + 1) % SIZE = (0 + 1) % 4 = 1 % 4 = 1 Q.elements[1] := 42;


1 14 42

0
Front = 0

Rear = 1

3
10/25/2012 CS 09 303 Data Structures - Module 2

2
137

Enqueue (20, Q) Rear := (rear + 1) % SIZE = (1 + 1) % 4 = 2 % 4 = 2 Q.elements[2] := 20;


1 14 42

0
Front = 0

20 3
10/25/2012 CS 09 303 Data Structures - Module 2

Rear = 2
138

Enqueue (37, Q) Rear := (rear + 1) % SIZE = (2 + 1) % 4 = 3 % 4 = 3 Q.elements[3] := 37;


0
Front = 0

1 14 42

Queue full
20 2
CS 09 303 Data Structures - Module 2 139

37
Rear = 3
10/25/2012

Queue full front := (rear + 1) % SIZE = (3 + 1) % 4 = 4 % 4 = 0


0
Front = 0

1 14 42

37
Rear = 3
10/25/2012

20 2

3
CS 09 303 Data Structures - Module 2

140

Deletion Function DEQUEUE(Var Q : QUEUE): elementtype; begin if Q.front = -1 then begin error(Queue is empty) exit(); end else dequeue := Q.elements[Q.front]; Q.front := (Q.front + 1) % SIZE; end;{DEQUEUE}

10/25/2012

CS 09 303 Data Structures - Module 2

141

Is this situation possible in a circular queue?

10/25/2012

CS 09 303 Data Structures - Module 2

142

Double-ended Queue (DEQUEUE)


Homogeneous list Insertion &deletion can be done at both ends. 2 types of dequeue: (1) Input restricted queue (insertion: rear end deletion: both ends) An input-restricted dequeue is one where deletion can be made from both ends, but insertion can only be made at one end. (2)Output restricted queue (insertion: both ends deletion: front end) An output-restricted dequeue is one where insertion can be made at both ends, but deletion can be made from one end only.
10/25/2012 CS 09 303 Data Structures - Module 2 143

Operations on Dequeue
(1) Add an element at the rear end ( insert right) (2)Delete an element from the front end ( delete left ) (3) Add an element at the front end ( insert left ) (4) Delete an element from the rear end (delete right )

10/25/2012

CS 09 303 Data Structures - Module 2

144

Insert an element at the right side of dequeue


procedure insertRightDequeue(Var data: integer, Var Q: QUEUE); Begin read(data); if ((Q.left = 0 && Q.right = MAX - 1) || (Q.left = Q.right + 1)) then begin error(Queue overflow ); exit(); end;

10/25/2012 CS 09 303 Data Structures - Module 2 145

if Q.left = -1 then begin Q.left := 0; Q.right := 0; end else begin if Q.right = MAX-1 then Q.right := 0; else Q.right := Q.right+1; end; Q.elements[Q.right] := data; end; {insertRightDequeue}

10/25/2012

CS 09 303 Data Structures - Module 2

146

Insert an element at the right side of dequeue


Empty Queue (If left = right = -1)
0 1 2 3

l r

10/25/2012

CS 09 303 Data Structures - Module 2

147

insertRightDequeue ( 5, Q) Set left = 0, right = 0; Insert at 0. Q.elements[right] : = Q.elements[0] = 5;


0 5 left = 0 right = 0 1 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

148

insertRightDequeue ( 2, Q) Increment right. Right := right + 1 = 0 + 1 = 1; Insert at right. Q.elements[right] : = Q.elements[1] = 2;


0 5 left = 0 1 2 right = 1 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

149

insertRightDequeue ( 10, Q) Increment right. Right := right + 1 = 1 + 1 = 2; Insert at right. Q.elements[right] : = Q.elements[2] = 10;
0 5 left = 0 1 2 2 10 right = 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

150

insertRightDequeue ( 17, Q) Increment right. Right := right + 1 = 2 + 1 = 3; Insert at right. Q.elements[right] : = Q.elements[3] = 17;
0 5 left = 0 1 2 2 10 3 17 right = 3

Queue full (left = 0 and right = MAX 1 = 4 1 = 3)

10/25/2012

CS 09 303 Data Structures - Module 2

151

Perform a delete operation. So, left will be incremented by one. left := left + 1 = 0 + 1 = 1;

1 2 left = 1

2 10

3 17 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

152

insertRightDequeue (15, Q) 15 can be inserted at 0. If left <> -1 and right = MAX 1, there are vacant positions at the beginning of the queue. Set right = 0 and insert at 0.
0 15 right = 0 1 2 left = 1 2 10 3 17

Queue full (left = right + 1= 0 + 1 = 1)

10/25/2012

CS 09 303 Data Structures - Module 2

153

Insert an element at the left side of dequeue


procedure insertLeftDequeue(Var data:integer, Var Q: QUEUE); Begin read(data); if((Q.left = 0 && Q.right = MAX - 1) | | (Q.left = Q.right+1)) then begin error(Queue overflow ); exit(); end

10/25/2012

CS 09 303 Data Structures - Module 2

154

if Q.left = -1 then begin Q.left := 0; Q.right := 0; end else begin if Q.left = 0 then Q.left := MAX-1; else Q.left := Q.left-1; end; Q.elements[Q.left] := data; end; {insertLeftDequeue}
10/25/2012 CS 09 303 Data Structures - Module 2 155

Insert an element at the left side of dequeue


Empty Queue (If left = right = -1)
0 1 2 3

l r

10/25/2012

CS 09 303 Data Structures - Module 2

156

insertLeftDequeue ( 5, Q) Set left = 0, right = 0; Insert at 0. Q.elements[left] : = Q.elements[0] = 5;


0 5 left = 0 right = 0 1 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

157

insertLeftDequeue ( 2, Q) If left = 0, set left = MAX - 1. left := MAX - 1 = 4 - 1 = 3; Insert at left. Q.elements[left] : = Q.elements[3] = 2;
0 5 right = 0 1 2 3 2 left = MAX- 1

10/25/2012

CS 09 303 Data Structures - Module 2

158

insertLeftDequeue ( 10, Q) Decrement left. left := left - 1 = 3 - 1 = 2; Insert at left. Q.elements[left] : = Q.elements[2] = 10;
0 5 right = 0 1 2 10 left = 2 3 2

10/25/2012

CS 09 303 Data Structures - Module 2

159

insertLeftDequeue ( 17, Q) Decrement left. left := left - 1 = 2 - 1 = 1; Insert at left. Q.elements[left] : = Q.elements[1] = 17;
0 5 right = 0 1 17 left = 1 2 10 3 2

Queue full (left = right + 1 = 0 + 1 = 1)

10/25/2012

CS 09 303 Data Structures - Module 2

160

Perform a delete operation. Right will be set to MAX 1 so that element at zero is deleted first. right := MAX - 1 = 4 - 1 = 3;

1 17 left = 1

2 10

3 2 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

161

insertLeftDequeue (15, Q) 15 can be inserted at 0. If left <> -1 and left <> 0, there are vacant positions at the beginning of the queue. Set left := left - 1 = 2 -1 = 0 and insert at 0.
0 15 left = 0 1 2 2 10 3 17 right = 3

Queue full (left = 0 and right = MAX - 1)

10/25/2012

CS 09 303 Data Structures - Module 2

162

Dequeue Operations(Normal Queue Operations)


Insert Right (Rear) and Delete Left (Front) Insert Left (Front) and Delete Right (Rear)

10/25/2012

CS 09 303 Data Structures - Module 2

163

Delete an element from the right side of dequeue


procedure deleteRightDequeue(Var Q: QUEUE); Begin Var data: integer; if((Q.left = -1) then begin error(Queue underflow ); exit(); end;{if} data := Q.elements[Q.right];
10/25/2012 CS 09 303 Data Structures - Module 2 164

if (Q.left = Q.right ) then begin {only one element} Q.left:= -1; Q.right := -1; end;{if} if (Q.right = 0) then Q.right = MAX -1; else Q.right = Q.right -1; end; { deleteRightDequeue}

10/25/2012

CS 09 303 Data Structures - Module 2

165

Delete an element from the right side of dequeue

deleteRightDequeue ( Q) Right = 0. So, delete the first element. data := Q.elements[right] = Q.elements[0] = 5; Set Right := MAX - 1 = 3; {Next deletion occurs at right = 3}.
0 5 right = 0 1 2 left = 1 2 10 3 17

10/25/2012

CS 09 303 Data Structures - Module 2

166

deleteRightDequeue ( Q) Right = 3. data := Q.elements[right] = Q.elements[3] = 17; Set Right := right - 1 = 3 1 = 2;


0 1 2 left = 1 2 10 3 17 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

167

deleteRightDequeue ( Q) Right = 2. data := Q.elements[right] = Q.elements[2] = 10; Set Right := right - 1 = 2 1 = 1;


0 1 2 left = 1 2 10 right = 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

168

deleteRightDequeue (Q) data : = Q.elements[right] : = Q.elements[1] = 5; Left = right = 1; {only one element} Set left := -1, right := -1; {Queue becomes empty}
0 1 2 left = 1 right = 1 2 3

10/25/2012

CS 09 303 Data Structures - Module 2

169

deleteRightDequeue (Q) Empty Queue (left = right = -1) Cannot perform deletion

l r

10/25/2012

CS 09 303 Data Structures - Module 2

170

Delete an element from the left side of dequeue


procedure deleteLeftDequeue(Var data:integer,Var Q: QUEUE); Begin if((Q.left = -1) then begin error(Queue underflow ); exit(); end;{if} data:=Q.elements[Q.left];
10/25/2012 CS 09 303 Data Structures - Module 2 171

if Q.left = Q.right then begin {only one element} Q.left:= -1; Q.right := -1; end;{if} if ( Q.left = MAX - 1 ) then Q.left = 0; else Q.left = Q.left + 1; end; { deleteLeftDequeue}

10/25/2012

CS 09 303 Data Structures - Module 2

172

Delete an element from the left side of dequeue


deleteLeftDequeue ( Q) Left = 0. So, delete the first element. data := Q.elements[left] = Q.elements[0] = 12; Set left := left + 1 = 1; {Next deletion occurs at left = 1}.
0 12 left = 0 1 27 2 60 3 18 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

173

deleteLeftDequeue ( Q) Left = 1. data := Q.elements[left] = Q.elements[1] = 27; Set left := left + 1 = 1 + 1 = 2;


0 1 27 left = 1 2 60 3 18 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

174

deleteLeftDequeue ( Q) Left = 2. data := Q.elements[left] = Q.elements[2] = 60; Set left := left + 1 = 2 + 1 = 3;


0 1 2 60 left = 2 3 18 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

175

deleteLeftDequeue (Q) data : = Q.elements[left] : = Q.elements[3] = 18; Left = right = 3; {only one element} Set left := -1, right := -1; {Queue becomes empty}
0 1 2 3 18 left = 3 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

176

deleteLeftDequeue (Q) Empty Queue (left = right = -1) Cannot perform deletion

l r

10/25/2012

CS 09 303 Data Structures - Module 2

177

Example
Insert right (rear)

0 21 left = 0 right = 0

10/25/2012

CS 09 303 Data Structures - Module 2

178

Insert left (front)

0 21 right = 0

3 42 left = 3

10/25/2012

CS 09 303 Data Structures - Module 2

179

Insert right (rear)

0 21

1 35 right = 1

3 42 left = 3

10/25/2012

CS 09 303 Data Structures - Module 2

180

Insert left (front)

0 21

1 35 right = 1

2 5 left = 2

3 42

10/25/2012

CS 09 303 Data Structures - Module 2

181

Delete left (front)

0 21

1 35 right = 1

3 42 left = 2

10/25/2012

CS 09 303 Data Structures - Module 2

182

Delete right (rear)

0 21 right = 0

3 42 left = 2

10/25/2012

CS 09 303 Data Structures - Module 2

183

Delete right (rear)

3 42 left = 2 right = 3

10/25/2012

CS 09 303 Data Structures - Module 2

184

Delete left (rear)

l ,r = -1

10/25/2012

CS 09 303 Data Structures - Module 2

185

PRIORITY QUEUE
Collection of elements such that each element is assigned a priority number. Rules are: An element of higher priority is processed before any element of lower priority. Elements of same priority are processed according to the order in which they were added into the queue.

10/25/2012

CS 09 303 Data Structures - Module 2

186

Two types of priority queues


Ascending priority queue
Items are inserted arbitrarily and element with least priority is removed.

Descending priority queue


Items are inserted arbitrarily and element with highest priority is removed.

10/25/2012

CS 09 303 Data Structures - Module 2

187

Implementation
Implementation of priority queue: (1) One way list representation (2) Multiple Queues (one for each priority - Array representation) (3) Maximum or minimum heap

10/25/2012

CS 09 303 Data Structures - Module 2

188

One Way List Representation


Each node contains: INFO: Information field PRT : Priority number NEXT: Next pointer A node x precedes a node y in the list when x has higher priority than y or when both have same priority but x was inserted before y.

10/25/2012

CS 09 303 Data Structures - Module 2

189

Operations performed: Searching an element with maximum priority Inserting an element Deleting an element with maximum priority

10/25/2012

CS 09 303 Data Structures - Module 2

190

Insert A with priority number 2.

Start

A 2 NULL

10/25/2012

CS 09 303 Data Structures - Module 2

191

Insert B with priority number 1.

Start

B 1

A 2 NULL

10/25/2012

CS 09 303 Data Structures - Module 2

192

Insert C with priority number 2.

Start

B 1

A 2

C 2 NULL

10/25/2012

CS 09 303 Data Structures - Module 2

193

Delete operation deletes element with highest priority.

Start

B 1

A 2

C 2 NULL

10/25/2012

CS 09 303 Data Structures - Module 2

194

Delete operation deletes element with highest priority.

Start

A 2

C 2 NULL

10/25/2012

CS 09 303 Data Structures - Module 2

195

Insertion algorithm of one way list representation of priority queue


(1) Traverse the one way list until you find a node X

whose priority number exceeds N (item to be inserted).


(2) Insert ITEM N in front of node X. (3) If no such node is found, insert ITEM as the last element

of the list.

10/25/2012

CS 09 303 Data Structures - Module 2

196

Deletion algorithm of one way list representation of priority queue


(1) Set ITEM := INFO[START] { This saves the data in the

first node }
(2) Delete first node from the list (3) Process ITEM (4) Exit

10/25/2012

CS 09 303 Data Structures - Module 2

197

Array Implementation
As multiple queues. Multiple queues are defined in the same array queue[] of size n. Each queue i is allocated a predefined space bounded by array indices. A queue is maintained for each priority. In order to process an element of the priority queue, element from non-empty highest priority number queue is accessed.
10/25/2012 CS 09 303 Data Structures - Module 2 198

front[0]

rear[0] front[1]

rear[1] front[2]

rear[2] front[3]

rear[3]

Queue1

Queue2

Queue3

Queue4

10/25/2012

CS 09 303 Data Structures - Module 2

199

Insertion algorithm of array representation of priority queue


(1) Insert ITEM as the rear element in row M of QUEUE. (2)Exit

10/25/2012

CS 09 303 Data Structures - Module 2

200

Deletion algorithm of array representation of priority queue


(1)Find the smallest k such that FRONT[K]!=NULL. {Find the first non-empty queue} (2)Delete and process the front in row k of queue. (3) Exit

10/25/2012

CS 09 303 Data Structures - Module 2

201

Comparison of array & one way list representation


Array :Time efficient One way list :Space efficient

10/25/2012

CS 09 303 Data Structures - Module 2

202

Applications of Queue
Round robin techniques :Process scheduling Print server routines All types of customer service software(Railway/airticket reservation)

10/25/2012

CS 09 303 Data Structures - Module 2

203

Application of linked lists Polynomial Manipulation


Polynomial of single variable of degree m f(x) = amxm + am-1xm-1 + + aixi + + a1x + a0 ai are non-zero coefficients with exponents i. Each term is represented by a node with three fields, which represent the coefficient, exponent of a term and a pointer to the next term.

10/25/2012

CS 09 303 Data Structures - Module 2

204

A term of a polynomial of single variable x:


powerx coef next

p = 6x5 + 2x3 + x + 4 Store the polynomial in descending order of powers.


5 6 1570 1526 3 2 1607 1570 1 1 1750 1607 0 4 NULL 1750

10/25/2012

CS 09 303 Data Structures - Module 2

205

A term of a polynomial of variables x, y, z:


Power x Power y Power z coef next

p = 2x3 + 3xy + y2 + yz Store the polynomial such that terms are arranged in descending order of powers of x first, then y and then z.
3002 1103 0201 0111

10/25/2012

CS 09 303 Data Structures - Module 2

206

Addition of Two Polynomials of Single variable


p = 6x5 + 2x3 + x + 4 q = 2x4 + 10 x + 1
6x5 6x5 + + 2x4 2x4 2x3 + + 2x3 + + x + 4 1 5

10 x + 11 x +

10/25/2012

CS 09 303 Data Structures - Module 2

207

5 6 1570
ptrp

3 2 1607 1570 1 10 1700 1660

1 1 1750 1607 0 1 NULL 1700

0 4 NULL 1750

1526

4 2 1660
ptrq

1500

p.powerx > q.powerx (Add first term of p. Increment ptrp)


5 6
ptrr

1826

10/25/2012

CS 09 303 Data Structures - Module 2

208

5 6 1570 1526 4 2 1660


ptrq

3 2 1607
ptrp

1 1 1750 1607 0 1 NULL 1700

0 4 NULL 1750

1570

1 10 1700 1660

1500

p.powerx < q.powerx


5 6 1870 1826
ptrr

4 2 Null 1870

10/25/2012

CS 09 303 Data Structures - Module 2

209

5 6 1570 1526 4 2 1660 1500

3 2 1607
ptrp

1 1 1750 1607 0 1 NULL 1700

0 4 NULL 1750

1570

1 10 1700
ptrq

1660

p.powerx > q.powerx


5 6 1870 1826 4 2 1860 1870
ptrr

3 2 Null 1860

10/25/2012

CS 09 303 Data Structures - Module 2

210

5 6 1570 1526 4 2 1660 1500

3 2 1607 1570 1 10 1700


ptrq

1 1 1750
ptrp

0 4 NULL 1750

1607

0 1 NULL 1700

1660

p.powerx = q.powerx (Add the coefficients and increment both the pointers)
5 6 1870 1826 4 2 1860 1870 3 2 1807 1860
ptrr

1 11 Null 1807

10/25/2012

CS 09 303 Data Structures - Module 2

211

5 6 1570 1526 4 2 1660 1500

3 2 1607 1570 1 10 1700 1660

1 1 1750 1607 0 1 NULL


ptrq

0 4 NULL
ptrp

1750

1700

p.powerx = q.powerx (Add the coefficients)


5 6 1870 1826 4 2 1860 1870 3 2 1807 1860 1 11 1950 1807 0 5
10/25/2012 CS 09 303 Data Structures - Module 2

NULL 1950
212

ptrr

Algorithm for polynomial addition (single variable)


1. Repeat upto step 3 while there are terms in both polynomials yet to be processed. 2. Obtain values for terms from each polynomial. 3. If the powers associated with the two terms are equal then If the sum of coefficients of both terms is not zero then Insert sum of the coefficients into the sum polynomial. Obtain the next terms from both polynomials.

10/25/2012

CS 09 303 Data Structures - Module 2

213

Else if the power of first polynomial > power of the second polynomial then
Insert the term from first polynomial into sum polynomial. Obtain the next term in the first polynomial.

Else
Insert the term from second polynomial into sum polynomial. Obtain the next term in the second polynomial. 4. Copy remaining terms from non-empty polynomial into sum polynomial. 5. Return the address of the sum polynomial.
10/25/2012 CS 09 303 Data Structures - Module 2 214

Thank You

10/25/2012

CS 09 303 Data Structures - Module 2

215