版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Chapter3List, Stacks, and QueueIntroduce the concept of Abstract Data Types(ADTS). show how to efficiently perform operations on lists.Introduce the stack ADT and its use in implementingrecursion.Introduce the queue ADT and its use in operatingsystems and algorithm design.3.1 Abstract Data Types(ADT
2、S)1.ADT-a set of objects together with a set of operaions. Abstract data types are mathematical abstractions;nowhere in an ADTs definition is there any mention of how the set of operations is implemented.3.1 Abstract Data Types(ADTS)2. data object-a setof instances or values for example:Boolean=fals
3、e,trueDigit=0,1,2,3,4,5,6,7,8,9Letter=A,B,Z,a,b,z NaturalNumber=0,1,2,Integer = 0, +1, -1, +2, -2, +3, -3, String=a,b,aa, ab, ac,3.1 Abstract Data Types(ADTS)3data structureis a data object together with the relationships among the instances and among the individual elements that compose an instance
4、Data_Structure=D,RD-data object,R -a set of relationships of all the data members in D.3.2The List ADTL = (e1, e2, e3, , en) list size is nif n=0:empty list if n(finite)0:e1 is the first elementen is the last elementeiprecedesei+13.2The List ADTExample:Students=(Jack, Jill, Abe, Henry, Mary, , Judy)
5、Exams =(exam1, exam2, exam3)Days of Week = (S, M, T, W, Th, F, Sa) Months = (Jan, Feb, Mar, Apr, , Nov, Dec)3.2Operations:The List ADTCreate a linear listdetermine whether the list is empty determine the length of the list find the kth of the elementsearch for a given element delete the kth elementi
6、nsert a new element just after the kth3.2The List ADTADT specification of a linear listAbstractDateType LinearListinstancesordered finite collections of zero or more elements operationsCreate(); IsEmpty(); Find(k,x);Delete(k,x);Output(out);Destroy(); Length(); Search(x);Insert(k,x);3.2.1.Simple Arra
7、y Implementation of Lists1.Use an array to represent the instance of anobject(e1,e2,en)element012n-1MaxSize-1length=neach position of the array is called a cell or a nodemapping formula:location(i)=i-1O(1)e1e2e3en3.2.1.Simple Array Implementation of ListsSearch( x)O(length)L = (a,b,d,b,e)Search(d) =
8、 3Search(a) = 1Search(z) = 0ACN=(1+2+n)/n=(1+n)*n/(2n)=(n+1)/23.2.1.Simple Array Implementation of Listsremove( k,x)deletethe kth element and return it in xL = (a,b,c,d,e)delete(2,x)=L=(a,c,d,e),x=b,and index of c,d,e decrease by 1 delete(0) = errordelete(20) = errorO( n)3.2.1.Simple Array Implement
9、ation of Listsn-1AMN=(n-i-1)/n=(n-1+n-2+1+0)/n=(n-1)/2i=0e1e2en3.2.1.Simple Array Implementation of Listsinsert (x ,i)insert x after the ith elementL = (a,b,c,d,e,f,g) insert(0,h) =L = (h,a,b,c,d,e,f,g)index of a,b,c,d,e,f, and g increase by 1 insert(10,h) = errorinsert(-6,h) = error O( n)3.2.1.Simp
10、le Array Implementation of Lists012n-1nnAMN=(n-i)/(n+1)=(n+n-1+1+0)/(n+1)=n/2i=0e1e2en3.2.1.Simple Array Implementation of Lists2. Use array Implementation merit : easy Search.short coming :Insertion and Removing(Deletion) spenda lot of time.3.2.2.Linked ListsIn order to avoid the linear cost of ins
11、ertion and deletion.1)Each node of a data object keeps a link or apointer about the location of other relevant nodesL=(e1,e2,en)firstLink fieldData fieldnullene3e2e13.2.2.Linked ListsThe figure above is called a single linkedlist,and the structure is also called a chainA chain is a linked list in wh
12、ich each node represents one element.There is a link or pointer from one element to the next.The last node has a null pointer.3.2.2.Linked ListsDeletiona elementof a chainDelete(1,x)firstfirst = first.link;nulledcba3.2.2.Delete(3,x)Linked Listsfirstbeforefirst get to node just before node to be remo
13、vedbefore= first .link;nulledcccba3.2.2.Linked Listsnow change pointer in beforefirstpbbeforebefore .link = before .link .link;nulledca3.2.2.Linked Listsinsert operationinsert(0,f)firstnewNodeStep 1: get a node, set its data and link fields ChainNode newNode =new ChainNode(f, first);null edcbaf3.2.2
14、.Linked ListsfirstnewNodeStep 2: updatefirstfirst = newNode;fnulledcbainsert(3,f)firstnewNodefbefore1. first find node whose index is 32. next create a node and set its data and link fieldsChainNode newNode = new ChainNode(f,before .link);3.finally link before to newNodebefore .link = newNode;nulled
15、cbaTwo-Step insert(3,f)firstnewNodefbeforebefore = first .link .link; newNode .link = before .link; before .link = newNode;nulledcba3.2.3 Programming DetailsHeader (dummy node)1.headerheaderLenLe2e. Class definitionLinked ListsListNodeLinkedList代表结点的类都是包DataStructures的一部分代表表本身的类代表位置的类LinkedL
16、istItr)ListNode classLinked Listselement nextpackage DataStructures;class ListNodeListNode( object theElement)this( theElement, null);ListNode( object theElement, ListNode n)element = theElement;next = n;object element; ListNode next;) Iterator class for linked listsLinked Listscurrent
17、Lpackage DataStructurespublic class LinkedListItrLinkedListItr( ListNode theNode)current = theNode;public boolean isPastEnd( )return current = = null;public object retrieve( )return isPastEnd( ) ? Null : current.element;public void advance( )if( ! isPastEnd( ) )current = current.next;ListNode curren
18、t;3) LinkedList classheaderenLe2e1package DataStructures;public class LinkedListpublic LinkedList( )header = new ListNode( null ) ; public boolean isEmpty( )return header.next = = null ; public void makeEmpty( )header.next = null; public LinkedListItr zeroth( ) return new LinkedListItr( header ) ; p
19、ublic LinkedListItr first( ) return new LinkedListItr( header.next ) ; public LinkedListItr find( object x )public void remove( object x )public LinkedListItr findPrevious( object x ) public void insert( object x, LinkedListItr p )private ListNode header;Method to print a listpublic static void prin
20、tList( LinkedList theList )if ( theList.isEmpty( ) ) System.out.print( “Empty list” ) ;elseLinkedListItr itr = theList.first( );for( ; ! Itr.isPastEnd( ); itr. Advance( ) ) System.out.print( itr.retrieve( ) + “ “ ) ;System.out.println( );Operation:Constructors isEmpty makeEmptyZeroth and first retur
21、n iterators corresponding to the headerand first element.Find(x)publicLinkedListItrfind (object x)ListNode itr = header.next;while ( itr != null & !itr.element.equals( x ) ) itr = itr.next;return new LinkedListItr( itr );O(N)Remove( x )public void remove( object x )LinkedListItr p = findprevious( x
22、); if( p.current.next != null )p.current.next = p.current.next.next;O(1)Findprevious ( x )publicLinkedListItr findPrevious( object x )ListNode itr = header;while( itr.next !=null & !itr.next.element.equals( x ) itr = itr.next;return new LinkedListItr( itr );O(N)Insert(x, p)publicvoid insert( object
23、x, LinkedListItr p)if( p!=null & p.current != null )p.current.next = new ListNode( x, p.current.next );O(1)3.2.4.Doubly Linked ListsfirstNodelastNodeleft rightelementnulledcbnulla3.2.4.Doubly Linked Listsoperations:insertdelete3.2.4.Doubly Linked ListsDelete(1)firstNodelastNodepP=firstNode;firstNode
24、=p .right;firstNode .left=null;nulledcnullbnulla3.2.4.Doubly Linked ListsDelete(3)firstNodelastNodepP .left .right=p .right;P .right .left=p .left;nulledcbnulla3.2.4.Doubly Linked Listsinsert(0,f)firstNodelastNodefirstNode .left=newNode;newNodenewNode .left=null;firstNode=newNodenewNode .right=first
25、Node;nulledcbnullanullf3.2.4.Doubly Linked ListsnewNodeInsert(2,f)firstNodelastNodebeforeNodenewNode .left=beforeNode;newNode .right=beforeNode .right;beforeNode .right .left=newNode;beforeNode .right=newNode;nulledcbnulla3.2.4.Doubly Linked Circular ListsfirstNodeaedcbDoubly Linked Circular ListWit
26、h Header NodeheaderNodeedcbaEmpty Doubly Linked CircularList With HeaderNodeheaderNode3.2.5. Circular Linked Listsabcde3.2.5. Circular Linked ListsheaderabcdeheadNodeheaderheadNode例子:用循环链表求解约瑟夫(josephus)问题约瑟夫问题:实际上是一个游戏。书中以旅行社从n个旅客中选出一名旅客,为他提供免费旅行服务。例,n=8, m=3(报数)从1号开始报数出列顺序为:3, 6, 1, 5, 2,8, 4。最后一个
27、编号7的旅客将赢得旅游。18273645可由两种方法来解决:用数组来实现用循环链表来实现rearrear: 每次指向要出队列的前一个结点出队列的人也用链表来表示:head:指向出队列结点链表的开头结点p:指向出队列结点链表的尾结点以上rear, head, p都是ListNode的一个对象。nolink12n-1n1.2.w = m;for( int i = 1; i= n-1; i+)1) for (int j =1; j=w-1; j+)rear = rear.link; 2) if (i = = 1)head = rear.link ; p = head; elsep.link = re
28、ar.link; p = rear.link; 3) rear.link = p.link;P.link = rear; rear.link = null;3.实现该算法如果用数组来实现, 考虑一下如何做?3.2.6.Polynomial ADTExamples1.pn(x) = a0xe0+a1xe1+a2xe2+.+anxenArray implementationexample: p(x) = 3x4-5x3+8x2+2x-1coeffArrayp(x) = 2x1000+8x50-23-582-13.2.6.Linked list representations p1(x) = 10x
29、1000+5x14+1Examplesp2(x) = 3x1990-2x1492+11x+5expcoefp1p2polynomialoperations: addition , multiplication, and so on.50L111-214923199010L5141010001)Array implementation of the polynomial ADT012MAX-DEGREEcoeffArrayhighPowerpublic class Polynomialpublic Polynomial( ) zeroPolynomial( ); public void inse
30、rtTerm( int coef, int exp ) public void zeroPolynomial( )public Polynomial add( Polynomial rhs )public Polynomial multiply( Polynomial rhs ) throws Overflowpublic void print( )public static final int MAX-DEGREE = 100;private int coeffArray = new int MAX-DEGREE + 1; private int highPower = 0;public v
31、oid zeroPolynomial( )for( int i = 0; i=0; i-)sum.coeffArrayi = coeffArrayi + rhs.coeffArrayi ;return sum;Example:p1(x) = 3x8 5x3 + 3x 1 p2(x) = 4x6 + 2x2 + 20 1 2345 6 78202000400-130500003Public Polynomial multiply( Polynomial rhs ) throws overflowPolynomial product = new Polynomial( ); product.hig
32、hPower = highPower + rhs.highPower; if( product.highPower MAX-DEGREE )throw new overflow( );for( int i = 0; i= highPower; i+ )for( int j = 0; j= rhs.highPower; j+ )product.coeffArray i + j += coeffArrayi * rhs.coeffArrayj; return product;2)Class skeletons for linked list implemetation of the Polynom
33、ial ADTexpcoefp1p250L111-214923199010L514101000public class Literal/Vavious constractors(not shown) int coefficient;int exponent;public class Polynomialpublic Polynomial( ) /* Exercise */ public void insertTerm( int coef, int exp ) /* Exercise */ public void zeroPolynomial( ) /* Exercise */ public P
34、olynomial add( Polynomial rhs ) /* Exercise */ public Polynomial multiply( Polynomial rhs ) /* Exercise */ public void print( ) /* Exercise */ private List terms; /* A List of Literals, sorted by exponent */多项式相加:*问题: A(X)=2X100+3X14+2X8+1B(X)= -2X100+8X14-3X10+10X6-XA(X) + B(X) = 11X14 3X10 + 2X8 +
35、 10X6 X + 1存放非零指数的系数与指数,因此每个结点有三个域组成。itemA:B:datalink-11106-310814-210010283142100coefexplinkA(X)+B(X)=A(X)具体实现时,并不要再重新申请结点,完全利用原来两个链表的结点。方法:设4个引用变量:pa,pb,pc,p(c+需要)1) 初始化:pc , pa , pb ;2) 当pa和pb都有项时pc永远指向相加时结果链表的最后一个结点。a)指数相等( pa. exp= =pb. exp )对应系数相加:pa. coef=pa. coef + pb. coef ;p= pb(c+需要) ;pb前
36、进 ;if (系数相加结果为0)p=pa;pa前进; else pc. link=pa; pc=pa; pa前进b)指数不等pa. exp pb. exp/pa要插入结果链表pc. link=pa ; pc=pa ; pa前进3)当两链表中有一链表为空,则将另一链表链入结果链表就可以if (pb空了) pc. link=pa;elsepc. link=pb;算法分析:设两个多项式的项数分别是m和n,则总的比较次数为O(m+n)最坏情况下:两个多项式的指数项都不等且交叉递增,如a5x5+a3x3+a1x+a0b4x4+b2x2+b0A(x):B(x):m=4n=3比较m+n-1次2009年考研统
37、考题(15分)已知一个带有表头结点的单链表,结点结构为, 假设该链表只给出了头指针 list. 在不改变链表的前提下, 请设计一个尽可能高效的算法,查找链表中倒数第k个位置上的结点(k为正整数). 若查找成功,算法输出该结点的data域的值, 并返回1; 否则返回0.要求:1)2)3)描述算法的基本设计思想;描述算法的详细实现步骤;根据设计思想和实现步骤,采用程序设计语言描述算法( 使用C或C+或JAVA语言实现),关键之处请给出简要注.释datalink3.2.6.Cursor implementation of Linked Listsuse array to implement link
38、ed list:elementnextcursorSpaceelement012345678headernext0123pP = p.nextp.datap = cursorSpacep.nextcuesorSpacep.data123463025036781578101042017853.2.6.Cursor implementation of Linked Lists1)Node and iterator for cursor implemetation of linked listsclass CursorNodeCursorNode( object theElement )this(
39、theElement, 0 );CursorNode( object theElement, int n )element = theElement; next = n;object element;int next;3.2.6.Cursor implementation of Linked Listspublic class CursorListItrCursorListItr( int theNode ) current = theNode; public boolean isPastEnd( ) return current = = o; public object retrieve(
40、) return isPastEnd( ) ? null:CursorList.cursorSpace current .element;public void advance( )if( !isPastEnd( )current = CursorList.cursorSpace current .next;int current;3.2.6.Cursor implementation of Linked Lists2) Class skeleton for CursorListpublic class CursorListprivate static int alloc( ) private
41、 static void free( int p)public CursorList( ) header = alloc( );cursorSpace header .next = 0; public boolean isEmpty( ) return cursorSpace header .next = = 0; public void makeEmpty( )public CursorListItr zeroth( )return new CursorListItr( header ); public CursorListItr first( )return new CursorListI
42、tr( cursorSpace header .next ); public CursorListItr find( object x )public void insert( object x, CursorListItr p) public void remove( object x )public CursorListItr findPrevious( object x )private int header;static CursorNode cursorSpace;private static final int SPACE-SIZE = 100;staticcursorSpace
43、= new CursorNode SPACE-SIZE ; for( int i = 0; iSPACE-SIZE; i+)cursorSpace i = new CursorNode( null, i + 1 ); cursorSpace SPACE-SIZE-1.next = 0;3.2.6.Cursor implementation of Linked ListsSome Routines:Alloc and freeprivate static int alloc( )int p = cursorSpace 0 .next; cursorSpace0.next = cursorSpac
44、ep.next; if( p = = 0 )throw new OutOfMemoryError( );return p;private static void free( int p )cursorSpacep.element = null;cursorSpacep.next = cursorSpace0.next; cursorSpace0.next = p;3.2.6.Cursor implementation of Linked ListsFind routine-cursor implementationpublic CursorListItr find( object x )int itr = cursorSpace header .next;while( itr != cursorSpace itr .element.equals( x ) ) itr = cursorSpace itr .next;return new CursorListItr( itr );3.2.6.Cursor implementation of Linked ListsInsertion routine
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 企业所得税2026年度测试卷(含答案解析)
- 安徽宿州市埇桥区2026-2027学年七年级上学期11月期中英语试题(含答案)
- 人口与计划生育招考笔试试卷(含答案解析)
- 亚马逊包装知识考核测试题(含参考答案与详细解析)
- 初中九年级科学《简单机械与机械效率》教学设计
- 沪教版新五年级英语Unit 2暑假导学与巩固教学设计
- 初中生物七年级藻类与植物类群中考特训教案
- 高一语文必修上册第二单元古诗词复习教学设计
- 的化验员技能考核试题及答案
- 出租汽车安全知识竞赛题及答案
- 2026年世界艾滋病日主题班会
- 《劳动合同法配套执行规范》核心条款解析
- 2026年秋季新版苏教版四年级上册科学第五单元 研究磁铁(16-18课)教案
- 2026年秋季初中家长会 关注青春期心理健康
- 装配式叠合板安装监理实施细则
- 2026年成都蜀华初一入学英语分班考试真题含答案
- 2026年4月自考13477电子商务系统分析与设计试题试题及答案
- 2026届广东省广州市荔湾区统考毕业升学考试模拟卷英语卷含答案
- (2025年)昆明市官渡区社工考试真题及答案
- SQCDM培训教学课件
- GB 29539-2025家用和类似用途吸油烟机与换气扇能效限定值及能效等级
评论
0/150
提交评论