4-1 Deque (25分)

原题链接http://pta.patest.cn/pta/test/16/exam/3/question/696

4-1 Deque (25分)
A “deque” is a data structure consisting of a list of items, on which the following operations are possible:

Push(X,D): Insert item X on the front end of deque D.
Pop(D): Remove the front item from deque D and return it.
Inject(X,D): Insert item X on the rear end of deque D.
Eject(D): Remove the rear item from deque D and return it. Write routines to support the deque that take O(1) time per operation.
Format of functions:

Deque CreateDeque();
int Push( ElementType X, Deque D );
ElementType Pop( Deque D );
int Inject( ElementType X, Deque D );
ElementType Eject( Deque D );
where Deque is defined as the following:

typedef struct Node *PtrToNode;
struct Node {
ElementType Element;
PtrToNode Next, Last;
};
typedef struct DequeRecord *Deque;
struct DequeRecord {
PtrToNode Front, Rear;
};
Here the deque is implemented by a doubly linked list with a header. Front and Rear point to the two ends of the deque respectively. Front always points to the header. The deque is empty when Frontand Rear both point to the same dummy header. Note: Push and Inject are supposed to return 1 if the operations can be done successfully, or 0 if fail. If the deque is empty, Pop and Eject must returnERROR which is defined by the judge program.

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

#define ElementType int
#define ERROR 1e5
typedef enum { push, pop, inject, eject, end } Operation;

typedef struct Node *PtrToNode;
struct Node {
    ElementType Element;
    PtrToNode Next, Last;
};
typedef struct DequeRecord *Deque;
struct DequeRecord {
    PtrToNode Front, Rear;
};
Deque CreateDeque();
int Push( ElementType X, Deque D );
ElementType Pop( Deque D );
int Inject( ElementType X, Deque D );
ElementType Eject( Deque D );

Operation GetOp();          /* details omitted */
void PrintDeque( Deque D ); /* details omitted */

int main()
{
    ElementType X;
    Deque D;
    int done = 0;

    D = CreateDeque();
    while (!done) {
        switch(GetOp()) {
        case push: 
            scanf("%d", &X);
            if (!Push(X, D)) printf("Memory is Full!\n");
            break;
        case pop:
            X = Pop(D);
            if ( X==ERROR ) printf("Deque is Empty!\n");
            break;
        case inject: 
            scanf("%d", &X);
            if (!Inject(X, D)) printf("Memory is Full!\n");
            break;
        case eject:
            X = Eject(D);
            if ( X==ERROR ) printf("Deque is Empty!\n");
            break;
        case end:
            PrintDeque(D);
            done = 1;
            break;
        }
    }
    return 0;
}

/* Your function will be put here */

Sample Input:

Pop
Inject 1
Pop
Eject
Push 1
Push 2
Eject
Inject 3
End
Sample Output:

Deque is Empty!
Deque is Empty!
Inside Deque: 2 3

以下为答案,函数实现(C语言):

细节问题:
  1. D->Front始终为链表头指针,且头结点始终为空节点。D->Rear则不固定。
  2. 插入和删除一个节点时,务必考虑3种情况,Deque内为空时,Deque内只有一个元素时,和Deque内有多个元素时。
  3. 链表变动时,需要考虑当前插入节点的->Last和->Next,其前一个节点的->Next ,后一个节点的->Last,以及D->Front->Next和 D->Rear->Next与D->Rear->Last 这些变量在上述3种情况下是否需要改动。
Deque CreateDeque(){
    PtrToNode Temp_Node = (PtrToNode)malloc(sizeof(struct Node));
    Deque Temp_Record = (Deque)malloc(sizeof(struct DequeRecord));
 //   if(!Temp_Record||!Temp_Node)
 //       return -1;
    Temp_Node->Next = NULL;
    Temp_Node->Last = NULL;
    Temp_Record->Front = Temp_Node;
    Temp_Record->Rear = Temp_Node;
    return Temp_Record;
}


int Push( ElementType X, Deque D ){
    PtrToNode Temp_Node = (PtrToNode)malloc(sizeof(struct Node));
    if(!Temp_Node)
        return 0;
    Temp_Node->Element = X;
    Temp_Node->Last = D->Front;
    Temp_Node->Next = D->Front->Next;
    if(D->Front->Next)
        D->Front->Next->Last = Temp_Node;
    D->Front->Next = Temp_Node;
    if(D->Front == D->Rear)
        D->Rear = Temp_Node;
    return 1;
}


ElementType Pop( Deque D ){
    if(D->Front == D->Rear)
        return ERROR;
    PtrToNode Temp_Node = D->Front->Next;
    if(D->Front->Next == D->Rear)
        D->Rear = D->Front;
    D->Front->Next = D->Front->Next->Next;
    ElementType temp;
    temp = Temp_Node->Element;
    free(Temp_Node);
    return temp;
}
int Inject( ElementType X, Deque D ){
    PtrToNode Temp_Node = (PtrToNode)malloc(sizeof(struct Node));
    if(!Temp_Node)
        return ERROR;     
    Temp_Node->Element = X;
    Temp_Node->Next = NULL;
    D->Rear->Next = Temp_Node;
    Temp_Node->Last = D->Rear;
    if(D->Rear == D->Front)
        D->Front->Next = Temp_Node;
    D->Rear = Temp_Node;
    return 1;
}

ElementType Eject( Deque D ){
    if(D->Front == D->Rear)
        return ERROR;
    PtrToNode Temp_Node = D->Rear;
    ElementType temp = D->Rear->Element;
    D->Rear = D->Rear->Last;
    free(Temp_Node);
    return temp;
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
FILES ON DISKS -------------- DISK 1 ------ INSTALL EXE - Install program UNZIP EXE - Decompress .ZIP files README COM - Reads this README CLASSDBL ZIP - BIDSDBL PRJ - Project file for building classlibs TCLASDBL PRJ - Project file for building classlibs CLASSINC ZIP - ABSTARRY H - Header file for classlibs ARRAY H - Header file for classlibs ARRAYS H - Header file for classlibs ASSOC H - Header file for classlibs BAG H - Header file for classlibs BAGS H - Header file for classlibs BTREE H - Header file for classlibs CHECKS H - Header file for classlibs CLSDEFS H - Header file for classlibs CLSTYPES H - Header file for classlibs COLLECT H - Header file for classlibs CONTAIN H - Header file for classlibs DBLLIST H - Header file for classlibs DEQUE H - Header file for classlibs DEQUES H - Header file for classlibs DICT H - Header file for classlibs DLISTIMP H - Header file for classlibs HASHTBL H - Header file for classlibs LDATE H - Header file for classlibs LIST H - Header file for classlibs LISTIMP H - Header file for classlibs LTIME H - Header file for classlibs MEMMGR H - Header file for classlibs OBJECT H - Header file for classlibs PRIORTYQ H - Header file for classlibs QUEUE H - Header file for classlibs QUEUES H - Header file for classlibs RESOURCE H - Header file for classlibs SET H - Header file for classlibs SETS H - Header file for classlibs SHDDEL H - Header file for classlibs SORTABLE H - Header file for classlibs SORTARRY H - Header file for classlibs STACK H - Header file for classlibs STACKS H - Header file for classlibs STDTEMPL H - Header file for classlibs STRNG H - Header file for classlibs TIMER H - Header file for classlibs VECTIMP H - Header file for classlibs CLASSS ZIP - BIDSS PRJ - Project file for building classlibs TCLASSS PRJ - Project file for building classlibs CLASSSRC ZIP - ABSTARRY CPP - Abstract array class definitions ARRAY CPP - Source file for classlibs ASSOC CPP - Association class (used by dictionary class) BABSTARY CPP - Source file for classlibs BDICT CPP - Source file for Classlibs BSORTARY CPP - Source file for classlibs BTREE CPP - Tree class definitions BTREEINN CPP - Tree class definitions BTREELFN CPP - Tree class definitions COLLECT CPP - Ordered collection class definitions CONTAIN CPP - Container class definitions DBLLIST CPP - Doubly linked list class definitions DEQUE CPP - Source file for classlibs DICT CPP - Dictinary class definitiions HASHTBL CPP - Hash table class definitions LDATE CPP - Date class definitions LIST CPP - List class definitions LTIME CPP - Time class definitions MEMMGR CPP - Memory class definitions OBJECT CPP - Base class for other objects SORTARRY CPP - Sorted array class definitions STACK CPP - Source file for classlibs STRNG CPP - String class definitions TIMER CPP - Timer class definitions TMPLINST CPP - Timer class definitions CMDLINE CA2 - Split File of CMDLINE.ZIP EXAMPLES ZIP - BARCHART C - C example file CIRCLE CPP - C++ example file CIRCLE PRJ - Project file for CIRCLE.CPP CPASDEMO C - C example module for the Turbo Pascal - Turbo C++ interface demonstration CPASDEMO PAS - Pascal program that demonstrates Turbo Pascal - Turbo C++ interface CTOPAS CFG - Config file for Pascal - Turbo C++ interface demo CTOPAS PRJ - Project file for Turbo Pascal - Turbo C++ interface demo DCOPY CPP - C++ example file DEF CPP - C++ example module used by DICTION.CPP DEF H - Header file for DEF.CPP DEF2 CPP - C++ example - another version of DEF.CPP DEF2 H - Header file for DEF.CPP DICTION CPP - C++ example program DICTION H - Header file for DICTION.CPP DYNPOINT CPP - C++ example file DYNPOINT PRJ - Project file for DYNPOINT.CPP EX1 CPP - C++ example program EX2 CPP - C++ example program EX3 CPP - C++ example program EX4 CPP - C++ example program EX5 CPP - C++ example program EX5 PRJ - Project file for ex5.cpp EX6 CPP - C++ example program EX6 PRJ - Project file for ex6.cpp EX7 CPP - C++ example program EX7 PRJ - Project file for ex7.cpp EX8 CPP - C++ example program EX8 PRJ - Project file for ex8.cpp EX9 CPP - C++ example program EX9 PRJ - Project file for ex9.cpp FIGDEMO CPP - C++ example file FIGDEMO PRJ - Project file for FIGDEMO. CPP FIGURES CPP - C++ example file FIGURES H - Header file for FIGURES.CPP FILTER H - Header file for TASM2MSG.C and GREP2MSG.C GAME CPP - C example - simulated baseball game GETOPT C - Parses options in command line GREP2MSG C - Example program for Turbo C++ filters HELLO C - Example Turbo C++ program INTRO1 CPP - Example program from User's Guide INTRO10 CPP - Example program from User's Guide INTRO11 CPP - Example program from User's Guide INTRO12 CPP - Example program from User's Guide INTRO13 CPP - Example program from User's Guide INTRO14 CPP - Example program from User's Guide INTRO15 CPP - Example program from User's Guide INTRO16 CPP - Example program from User's Guide INTRO17 CPP - Example program from User's Guide INTRO18 CPP - Example program from User's Guide INTRO19 CPP - Example program from User's Guide INTRO2 CPP - Example program from User's Guide INTRO20 CPP - Example program from User's Guide INTRO21 CPP - Example program from User's Guide INTRO22 CPP - Example program from User's Guide INTRO23 CPP - Example program from User's Guide INTRO24 CPP - Example program from User's Guide INTRO25 CPP - Example program from User's Guide INTRO26 CPP - Example program from User's Guide INTRO27 CPP - Example program from User's Guide INTRO28 CPP - Example program from User's Guide INTRO29 CPP - Example program from User's Guide INTRO3 CPP - Example program from User's Guide INTRO30 CPP - Example program from User's Guide INTRO31 CPP - Example program from User's Guide INTRO32 CPP - Example program from User's Guide INTRO33 CPP - Example program from User's Guide INTRO34 CPP - Example program from User's Guide INTRO35 CPP - Example program from User's Guide INTRO36 CPP - Example program from User's Guide INTRO4 CPP - Example program from User's Guide INTRO5 CPP - Example program from User's Guide INTRO6 CPP - Example program from User's Guide INTRO7 CPP - Example program from User's Guide INTRO8 CPP - Example program from User's Guide INTRO9 CPP - Example program from User's Guide LIST CPP - C++ example program - linked list implementation LIST H - Header file for LIST.CPP LIST2 CPP - Another version of LIST.CPP LIST2 H - Header file for LIST2.CPP LISTDEMO CPP - C++ example file LISTDEMO PRJ - Project file for LISTDEMO.CPP MATHERR C - Source code for handling math library exceptions MCIRCLE CPP - C++ example file MCIRCLE PRJ - Project file for MCIRCLE.CPP PIXEL CPP - C++ example file PIXEL PRJ - Project file for PIXEL.CPP PLANETS CPP - C graphics example PLOTEMP C - C graphics example PLOTEMP1 C - C graphics example - bar graphs PLOTEMP2 C - C example - modification of PLOTEMP1.C PLOTEMP3 C - C example - modification of PLOTEMP2.C PLOTEMP4 C - C example - modification of PLOTEMP3.C PLOTEMP5 C - C example - modification of PLOTEMP4.C PLOTEMP6 C - C example - modification of PLOTEMP5.C POINT CPP - C++ example program POINT H - Header file for POINT.CPP POINT2 CPP - C++ example program SALESTAG C - C example program form User's Guide SOLAR CPP - C example program from User's Guide STACK CPP - Stack class definitions STACK H - Header file for STACK.CPP STACK2 CPP - Another version of STACK.CPP STACK2 H - Header file for STACK2.CPP STRING CPP - C++ example program TASM2MSG C - Example program for Turbo C++ filters VCIRC CPP - C++ example program VCIRC PRJ - Project file for VCIRC.CPP VPOINT CPP - C++ example program VPOINT H - Header file for VPOINT.CPP XSTRING CPP - C++ example program FILELIST DOC - List & description of files HELP CA2 - Split File of HELP.ZIP HELP CA3 - Split File of HELP.ZIP IDE CA2 - Split File of IDE.ZIP INCLUDE ZIP - Turbo C++ header files _DEFS H - Definition of _FAR, _Cdecl, _CType, _ClassType _NULL H - Definition of NULL ALLOC H - Turbo C++ RTL header file GRAPHICS H - Turbo C++ RTL header file ASSERT H - Turbo C++ RTL header file BCD H - Turbo C++ RTL header file BIOS H - Turbo C++ RTL header file COMPLEX H - Turbo C++ RTL header file CONIO H - Turbo C++ RTL header file CONSTREA H - Turbo C++ RTL header file CTYPE H - Turbo C++ RTL header file DIR H - Turbo C++ RTL header file DIRECT H - Turbo C++ RTL header file DIRENT H - Turbo C++ RTL header file DOS H - Turbo C++ RTL header file ERRNO H - Turbo C++ RTL header file FCNTL H - Turbo C++ RTL header file FLOAT H - Turbo C++ RTL header file FSTREAM H - Turbo C++ RTL header file GENERIC H - Turbo C++ RTL header file IO H - Turbo C++ RTL header file IOMANIP H - Turbo C++ RTL header file IOSTREAM H - Turbo C++ RTL header file LIMITS H - Turbo C++ RTL header file LOCALE H - Turbo C++ RTL header file LOCKING H - Turbo C++ RTL header file MALLOC H - Turbo C++ RTL header file MATH H - Turbo C++ RTL header file MEM H - Turbo C++ RTL header file MEMORY H - Turbo C++ RTL header file NEW H - Turbo C++ RTL header file PROCESS H - Turbo C++ RTL header file SEARCH H - Turbo C++ RTL header file SETJMP H - Turbo C++ RTL header file SHARE H - Turbo C++ RTL header file SIGNAL H - Turbo C++ RTL header file STAT H - Turbo C++ RTL header file STDARG H - Turbo C++ RTL header file STDDEF H - Turbo C++ RTL header file STDIO H - Turbo C++ RTL header file STDIOSTR H - Turbo C++ RTL header file STDLIB H - Turbo C++ RTL header file STRING H - Turbo C++ RTL header file STRSTREA H - Turbo C++ RTL header file TIME H - Turbo C++ RTL header file TIMEB H - Turbo C++ RTL header file TYPES H - Turbo C++ RTL header file UTIME H - Turbo C++ RTL header file VALUES H - Turbo C++ RTL header file VARARGS H - Turbo C++ RTL header file XLIB ZIP - EMU LIB - 8087 emulator library FP87 LIB - 8087 library OVERLAY LIB - Overlays library WILDARGS OBJ - Object code for module to expand wildcard arguments GRAPHICS LIB - Graphics library README - General information last minute changes to documentation DISK 2 ------ CLIB ZIP - C0C OBJ - Compact model startup code C0FC OBJ - Compact model startup code CC LIB - Compact model run-time library MATHC LIB - Compact model math library CMDLINE CA1 - OBJXREF COM - Conversion program for object files. BUILTINS MAK - File containing default inference rules and macros for MAKE.EXE CPP EXE - Turbo C++ preprocessor MAKE EXE - Protected mode version of program for managing projects MAKER EXE - Real mode version of program for managing projects TCC EXE - Command-line version of Turbo C++ Compiler TDUMP EXE - Utility to access internal file structure TLINK EXE - Turbo Linker HELP CA1 - TCHELP TCH - Turbo C++ help file THELP COM - On-line help program IDE CA1 - Files in Turbo C++ Compiler - IDE version TASM2MSG EXE - Display Tasm error msgs in IDE PRJCFG EXE - Utility to convert PRJ files TRANCOPY EXE - Utility to access transfer data GREP2MSG EXE - GREP filter program for IDE PRJCNVT EXE - Utility to convert from Turbo C 2.x project files to Turbo C++ project files TC PIF - Pif file for TC.EXE TC EXE - Turbo C++ compiler (IDE) TEMC EXE - Turbo editor macro compiler DISK 3 ------ BGI ZIP - ATT BGI - Graphics driver for ATT400 graphics card BGIDEMO C - Graphics demonstration program BGIOBJ EXE - Conversion program for fonts and drivers BOLD CHR - Font for Bold char set CGA BGI - Graphics driver for CGA EGAVGA BGI - Graphics driver for EGA and VGA EURO CHR - Font for European char set GOTH CHR - Font for gothic character set HERC BGI - Graphics driver for Hercules IBM8514 BGI - Graphics driver for IBM 8514 graphics card LCOM CHR - Complex char font set LITT CHR - Font for small character set PC3270 BGI - Graphics driver for PC3270 SANS CHR - Font for sans serif character set SCRI CHR - Font for script char set SIMP CHR - Font for Simplex char set TRIP CHR - Font for triplex character set TSCR CHR - Font for tiny script char set BIN ZIP - DPMI16BI OVL - Turbo C++ DPMI Server DPMIINST EXE - Turbo C++ DPMI Configuration program DPMILOAD EXE - Turbo C++ DPMI loader DPMIMEM DLL - Turbo C++ DPMI memory manager DPMIRES EXE - Turbo C++ DPMI resident loader(user executable) EMSTEST COM - Utility program for detecting expanded memory GREP COM - Turbo GREP program PRJ2MAK EXE - Utility to convert a TC project file into a TCC make file TLIB EXE - Turbo Librarian TOUCH COM - Program that updates a file's date and time TRIGRAPH EXE - Trigraph conversion utility CLASSDBS ZIP - BIDSDBS PRJ - Project file for building classlibs TCLASDBS PRJ - Project file for building classlibs CLASSEXM ZIP - DIRECTRY CPP - Directory class example file DIRECTRY H - Header file for DIRECTRY.CPP DIRECTRY PRJ - Project file for DIRECTRY.CPP FILEDATA CPP - FileData class example file FILEDATA H - Header file for FILEDATA.CPP LOOKUP CPP - Lookup table example file LOOKUP PRJ - Project file for LOOKUP.CPP QUEUETST CPP - Queue class example file QUEUETST PRJ - Project file for QUEUETST.CPP REVERSE CPP - String class example file REVERSE PRJ - Project file for REVERSE.CPP STRNGMAX CPP - String class example file STRNGMAX PRJ - Project file for STRNGMAX.CPP TESTDIR CPP - Directory example file CLASSL ZIP - BIDSL PRJ - Project file for building classlibs TCLASSL PRJ - Project file for building classlibs CLASSLIB ZIP - TCLASDBS LIB - Library file for C++ classes TCLASSS LIB - Library file for C++ classes DOC ZIP - BRIEF TEM - Editor Macros File for Brief emulation CMACROS TEM - Editor Macros File for C emulation DEFAULTS TEM - Sample Editor Macros File DOSEDIT TEM - Editor Macros File for Dosedit emulation EPSILON TEM - Editor Macros File for Epsilon emulation HELPME! DOC - Answers to commonly asked questions UTIL DOC - On-line documentation for utilities CLASSLIB DOC - On-line documentation for container classes ANSI DOC - On-line documentation for ansi compatability BASM DOC - On-line documentation for BASM HLIB ZIP - Huge model libraries C0H OBJ - Huge model startup code C0FH OBJ - Huge model startup code CH LIB - Huge model run-time library MATHH LIB - Huge model math library LLIB ZIP - Large model libraries C0L OBJ - Large model startup code C0FL OBJ - Large model startup code CL LIB - Large model run-time library MATHL LIB - Large model math library MLIB ZIP - Medium model libraries C0M OBJ - Medium model startup code C0FM OBJ - Medium model startup code CM LIB - Medium model run-time library MATHM LIB - Medium model math library SLIB ZIP - Small model libraries C0S OBJ - Small model startup code C0FS OBJ - Small model startup code C0T OBJ - Tiny model startup code C0FT OBJ - Tiny model startup code CS LIB - Small model run-time library MATHS LIB - Small model math library TCALC ZIP - Files for TCALC example program TCALC C - TurboCalc main program source code TCALC DOC - TurboCalc documentation TCALC H - The header file for TurboCalc TCALC PRJ - The TurboCalc project file TCDISPLY C - TurboCalc screen display source code TCINPUT C - TurboCalc input routines source code TCOMMAND C - TurboCalc commands source code TCPARSER C - TurboCalc input parser source code TCUTIL C - TurboCalc utilities source code
1.第9章 顺序容器 - STL deque 2.第9章 顺序容器 - STL list 3.第9章 9.7 容器适配器 - 栈适配器 4.第9章 9.7 容器适配器 - 队列 5.第9章 9.7 容器适配器 - 优先级队列 6.第9章 9.1 顺序容器的定义 7.第9章 9.2 迭代器和迭代器范围 8.第9章 9.3 顺序容器的操作(1) 9.第9章 9.3 顺序容器的操作(2) 10.第9章 9.3 顺序容器的操作(3) 11.第9章 9.3 顺序容器的操作(4) 12.第9章 9.3 顺序容器的操作(5) 13.第9章 9.3 顺序容器的操作(6) 14.第9章 9.3 顺序容器的操作(7) 15.第9章 9.4 vector容器的自增长 16.第9章 9.5 容器的选用 17.第9章 9.6 再谈string类型(1) 18.第9章 9.6 再谈string类型(2) 19.第9章 9.6 再谈string类型(3) 20.第9章 9.6 再谈string类型(4) 21.第9章 9.6 再谈string类型(5) 22.第10章 map 和 multimap 23.第10章 set 和 multiset 24.第11章 算法简介 25.第11章 函数对象简介 26.第11章 算法 元素计数 27.第11章 算法 最大值和最小值 28.第11章 算法 查找算法(1) 29.第11章 算法 查找算法(2) 30.第11章 算法 查找算法(3) 31.第11章 算法 查找算法(4) 32.第11章 算法 查找算法(5) 33.第11章 算法 查找算法(6) 34.第11章 算法 查找算法(7) 35.第11章 算法 for_each 36.第11章 算法 区间的比较 37.第11章 算法 复制元素 38.第11章 算法 transform 39.第11章 算法 比较for_each和transform 40.第11章 算法 交换算法 41.第11章 算法 填充新值 42.第11章 算法 替换算法 43.第11章 算法 删除算法 (1) 44.第11章 算法 删除算法 (2) 45.第11章 算法 删除算法 (3) 46.第11章 算法 逆转和旋转 47.第11章 算法 排列组合 48.第11章 算法 重排和区 49.第11章 算法 对所有元素排序 50.第11章 算法 局部排序 51.第11章 算法 根据第n个元素排序 52.第11章 算法 Heap算法
Data Structures Succinctly Part 1 Table of Contents The Story behind the Succinctly Series of Books ................................................................................... 9 Chapter 1 Algorithms and Data Structures ........................................................................................... 11 Why Do We Care? ................................................................................................................................. 11 Asymptotic Analysis ............................................................................................................................... 11 Rate of Growth ..................................................................................................................................... 11 Best, Average, and Worst Case .......................................................................................................... 13 What are we Measuring? ..................................................................................................................... 13 Code Samples ..................................................................................................................................... 13 Chapter 2 Linked List ............................................................................................................................... 14 Overview ................................................................................................................................................ 14 Implementing a LinkedList Class ........................................................................................................... 16 The Node ............................................................................................................................................. 16 The LinkedList Class ........................................................................................................................... 18 Add ....................................................................................................................................................... 19 Remove ................................................................................................................................................ 20 Contains ............................................................................................................................................... 22 GetEnumerator .................................................................................................................................... 23 Clear .................................................................................................................................................... 24 CopyTo ................................................................................................................................................ 24 Count ................................................................................................................................................... 25 IsReadOnly .......................................................................................................................................... 25 Doubly Linked List .................................................................................................................................. 25 Node Class .......................................................................................................................................... 26 Add ....................................................................................................................................................... 26 5 Remove ................................................................................................................................................ 28 But Why? ............................................................................................................................................. 31 Chapter 3 Array List ................................................................................................................................. 33 Overview ................................................................................................................................................ 33 Class Definition ...................................................................................................................................... 33 Insertion ................................................................................................................................................. 35 Growing the Array ................................................................................................................................ 35 Insert .................................................................................................................................................... 37 Add ....................................................................................................................................................... 38 Deletion .................................................................................................................................................. 39 RemoveAt ............................................................................................................................................ 39 Remove ................................................................................................................................................ 40 Indexing.................................................................................................................................................. 40 IndexOf ................................................................................................................................................ 40 Item ...................................................................................................................................................... 41 Contains ............................................................................................................................................... 42 Enumeration ........................................................................................................................................... 42 GetEnumerator .................................................................................................................................... 42 Remaining IList<T> Methods ................................................................................................................. 43 Clear .................................................................................................................................................... 43 CopyTo ................................................................................................................................................ 43 Count ................................................................................................................................................... 43 IsReadOnly .......................................................................................................................................... 44 Chapter 4 Stack and Queue .................................................................................................................... 45 Overview ................................................................................................................................................ 45 Stack ...................................................................................................................................................... 45 6 Class Definition .................................................................................................................................... 46 Push ..................................................................................................................................................... 47 Pop ....................................................................................................................................................... 47 Peek ..................................................................................................................................................... 48 Count ................................................................................................................................................... 48 Example: RPN Calculator .................................................................................................................... 49 Queue .................................................................................................................................................... 51 Class Definition .................................................................................................................................... 51 Enqueue ............................................................................................................................................... 52 Dequeue .............................................................................................................................................. 52 Peek ..................................................................................................................................................... 53 Count ................................................................................................................................................... 53 Deque (Double-Ended Queue) .............................................................................................................. 53 Class Definition .................................................................................................................................... 54 Enqueue ............................................................................................................................................... 55 Dequeue .............................................................................................................................................. 55 PeekFirst .............................................................................................................................................. 56 PeekLast .............................................................................................................................................. 57 Count ................................................................................................................................................... 57 Example: Implementing a Stack .......................................................................................................... 58 Array Backing Store ............................................................................................................................. 59 Class Definition .................................................................................................................................... 62 Enqueue ............................................................................................................................................... 62 Dequeue .............................................................................................................................................. 65 PeekFirst .............................................................................................................................................. 66 PeekLast .............................................................................................................................................. 66 Count ................................................................................................................................................... 67 7 Chapter 5 Binary Search Tree ................................................................................................................. 68 Tree Overview ........................................................................................................................................ 68 Binary Search Tree Overview ................................................................................................................ 69 The Node Class ..................................................................................................................................... 70 The Binary Search Tree Class ............................................................................................................... 71 Add ....................................................................................................................................................... 72 Remove ................................................................................................................................................ 74 Contains ............................................................................................................................................... 79 Count ................................................................................................................................................... 81 Clear .................................................................................................................................................... 81 Traversals .............................................................................................................................................. 82 Preorder ............................................................................................................................................... 82 Postorder ............................................................................................................................................. 83 Inorder .................................................................................................................................................. 84 GetEnumerator .................................................................................................................................... 86 Chapter 6 Set ............................................................................................................................................ 87 Set Class ................................................................................................................................................ 87 Insertion ................................................................................................................................................. 89 Add ....................................................................................................................................................... 89 AddRange ............................................................................................................................................ 89 Remove .................................................................................................................................................. 90 Contains ................................................................................................................................................. 90 Count ...................................................................................................................................................... 91 GetEnumerator ...................................................................................................................................... 91 Algorithms .............................................................................................................................................. 92 Union .................................................................................................................................................... 92 8 Intersection .......................................................................................................................................... 93 Difference ............................................................................................................................................. 94 Symmetric Difference .......................................................................................................................... 95 IsSubset ............................................................................................................................................... 96 Chapter 7 Sorting Algorithms ................................................................................................................. 98 Swap ...................................................................................................................................................... 98 Bubble Sort ............................................................................................................................................ 98 Insertion Sort ........................................................................................................................................ 100 Selection Sort ....................................................................................................................................... 103 Merge Sort ........................................................................................................................................... 105 Divide and Conquer ........................................................................................................................... 105 Merge Sort ......................................................................................................................................... 106 Quick Sort ............................................................................................................................................ 108
CHAPTER 1 About Python ............................................................................................1 What Is Python? ................................................................................................................1 A Brief History of Python ................................................................................................2 Interpreters Versus Compilers .......................................................................................5 When to Use (or Not Use) an Interpreted Language .........................................8 Understanding Bytecodes ......................................................................................10 Why Use Python? ...........................................................................................................11 Object-Oriented ........................................................................................................11 Cross Platform ..........................................................................................................11 Broad User Base .......................................................................................................11 Well Supported in Third-Party Tools ...................................................................12 Good Selection of Tools Available ........................................................................12 Good Selection of Pre-built Libraries ..................................................................12 Where Is Python Used? .................................................................................................13 How Is Python Licensed? ..............................................................................................13 Where Do I Get Python? ...............................................................................................14 Installing Python ............................................................................................................14 Getting Information on Python ..................................................................................16 Python Communities .....................................................................................................17 Other Software ................................................................................................................18 And Now for Something Completely Different… ....................................................18 CHAPTER 2 Python Language Overview .................................................................19 Python Syntax .................................................................................................................20 Comments .................................................................................................................20 Indentation ...............................................................................................................20 Contents TABLE OF} vii Q Q Q Python Reserved Words ................................................................................................24 Decision Making and Iteration Keywords ..........................................................25 Debugging Keywords ..............................................................................................27 Package and Module Handling Keywords .........................................................27 Exception Handling Keywords ..............................................................................29 General Language Keywords .................................................................................31 Other Keywords ........................................................................................................32 Variable Usage ................................................................................................................34 The Continuation Variable ....................................................................................36 Watching Out for Spelling Mistakes! ..................................................................37 Predicates .........................................................................................................................38 Identifier Scope ...............................................................................................................39 Operators .........................................................................................................................42 Modulo Operator .....................................................................................................44 Exponential Operator .............................................................................................46 Logical Operators ....................................................................................................46 Comparative Operators ..........................................................................................49 Bitwise Operators ....................................................................................................51 Membership Operators and String Operators ..................................................53 Identity Operators ...................................................................................................53 In Conclusion ..................................................................................................................53 CHAPTER 3 Tools ..........................................................................................................55 IDLE ...................................................................................................................................55 File Menu ...................................................................................................................57 The Path Browser Dialog ........................................................................................62 Edit Menu ..................................................................................................................64 Shell Menu .................................................................................................................70 Debug Menu ..............................................................................................................71 The Edit Window ......................................................................................................79 Format Menu ............................................................................................................80 CONTENTS viii Q Q Q Command Line Compiler ..............................................................................................90 Creating Python Files ....................................................................................................93 Documentation ...............................................................................................................95 In Conclusion ..................................................................................................................96 CHAPTER 4 Data Types ...............................................................................................97 Numeric Types ................................................................................................................98 Integers ......................................................................................................................98 Demonstrating Long Integers ...............................................................................99 Octal and Hexadecimal ........................................................................................100 Floating Point Numbers .............................................................................................101 Strings ............................................................................................................................103 String Variables .....................................................................................................103 Concatenating Strings .........................................................................................106 Repeating Strings ..................................................................................................107 Substrings ...............................................................................................................108 Slicing ......................................................................................................................110 String Functions ....................................................................................................111 String Constants ....................................................................................................112 Conversion Functions ...........................................................................................114 Search Functions ...................................................................................................118 Formatting Functions ..........................................................................................120 Escape Sequences ..................................................................................................121 Sequences ......................................................................................................................122 Lists ..........................................................................................................................123 Shared References .................................................................................................128 Tuples .......................................................................................................................128 Dictionaries ............................................................................................................132 Advanced Type .............................................................................................................136 Classes and Objects ..............................................................................................136 Complex Type .........................................................................................................137 Generator Type ......................................................................................................138 CONTENTS ix Q Q Q None Type ...............................................................................................................139 Unicode Type ..........................................................................................................140 In Conclusion ................................................................................................................141 CHAPTER 5 Control Flow .........................................................................................143 Conditionals ..................................................................................................................144 The if Statement ..................................................................................................144 The elif Statement .............................................................................................147 The else Statement .............................................................................................149 Wrapping Up the Conditionals: A Cool Example ...........................................150 Loops ..............................................................................................................................153 The for Loop ..........................................................................................................153 The while Loop .....................................................................................................161 In Conclusion ................................................................................................................164 CHAPTER 6 Input and Output ................................................................................165 User Input ......................................................................................................................165 The input Function ..............................................................................................166 The raw_input Function ....................................................................................168 User Output ...................................................................................................................170 Formatting ..............................................................................................................172 File Input .......................................................................................................................175 File Output ....................................................................................................................177 Closing Files ..................................................................................................................179 Positioning in Files ......................................................................................................180 Directories and Files ...................................................................................................183 The stat Module: File Statistics ..............................................................................186 Command Line Arguments ........................................................................................190 Pickle ..............................................................................................................................192 In Conclusion ................................................................................................................195 CONTENTS x Q Q Q CHAPTER 7 Functions and Modules .....................................................................197 What Is a Function? ....................................................................................................197 Defining Functions in Python ...................................................................................197 What Are Arguments? ................................................................................................200 How Do You Pass an Argument to a Function? ....................................................201 Default Arguments ......................................................................................................203 Variable Default Arguments .....................................................................................205 Keyword Arguments ....................................................................................................206 Returning Values from Functions ............................................................................207 Returning Multiple Values from Functions ...........................................................209 Recursive Functions ....................................................................................................210 Passing Functions as Arguments .............................................................................212 Lambda Functions .......................................................................................................213 Variable Numbers of Arguments to a Function ....................................................215 Variable Scope in Functions ......................................................................................216 Using Modules ..............................................................................................................218 In Conclusion ................................................................................................................219 CHAPTER 8 Exception Handling ............................................................................221 Looking at Exceptions in Python ..............................................................................222 Traceback Example ......................................................................................................223 Understanding Tracebacks ........................................................................................224 Exceptions .....................................................................................................................225 Catching Exceptions with try..except .........................................................226 Multiple except Clauses .....................................................................................229 Blank except Clauses ..........................................................................................231 The else Clauses .........................................................................................................232 The finally Clause ....................................................................................................234 Raising Your Own Exceptions ...................................................................................235 Exception Arguments .................................................................................................237 User-Defined Exceptions ............................................................................................238 Working with the Exception Information ..............................................................239 CONTENTS xi Q Q Q exc_type ................................................................................................................239 exc_value ..............................................................................................................240 Using the with Clause for Files ................................................................................243 Re-throwing Exceptions .............................................................................................244 In Conclusion ................................................................................................................246 CHAPTER 9 Object-Oriented Programming .........................................................247 A Brief History of OOP ................................................................................................247 What Is an Object? ......................................................................................................248 Why Do We Use Objects? ...........................................................................................249 Reuse ........................................................................................................................249 Ease in Debugging .................................................................................................250 Maintainability ......................................................................................................250 The Attributes of Object-Oriented Development .................................................251 Abstraction .............................................................................................................251 Data Hiding ............................................................................................................252 Inheritance .............................................................................................................253 Polymorphism ........................................................................................................255 Terminology ..................................................................................................................256 Class .........................................................................................................................256 Object .......................................................................................................................256 Attribute ..................................................................................................................257 Method ....................................................................................................................258 Message Passing ....................................................................................................259 Event Handling ......................................................................................................260 Derivation ...............................................................................................................260 Coupling ..................................................................................................................261 Cohesion ..................................................................................................................261 Constants ................................................................................................................261 Other Concepts .............................................................................................................262 In Conclusion ................................................................................................................262 CONTENTS xii Q Q Q CHAPTER 10 Classes and Objects in Python ..........................................................265 Python Classes ..............................................................................................................265 Properties ......................................................................................................................267 Attribute Modifying Functions .................................................................................272 Private Attributes ........................................................................................................274 Doc Strings ....................................................................................................................275 Properties ......................................................................................................................277 The self Object ...........................................................................................................279 Methods .........................................................................................................................281 Special Methods ...........................................................................................................283 Initialization ...........................................................................................................283 Termination ............................................................................................................284 String Conversion ..................................................................................................285 Inheritance ....................................................................................................................287 Multiple Inheritance ...................................................................................................291 Using super ..................................................................................................................293 Polymorphism ..............................................................................................................295 Exception Classes .........................................................................................................297 Iterators .........................................................................................................................299 Operator Overloading .................................................................................................301 In Conclusion ................................................................................................................304 CHAPTER 11 The Python Library ..............................................................................305 Containers .....................................................................................................................305 Working with the deque Class ...........................................................................306 Math ................................................................................................................................312 Complex Math ..............................................................................................................313 Types ...............................................................................................................................315 Strings ............................................................................................................................318 Regular Expressions ....................................................................................................319 Patterns ...................................................................................................................320 Special Sequence Characters ..............................................................................323 CONTENTS xiii Q Q Q Compiling Regular Expressions .........................................................................323 Matching Strings ...................................................................................................324 Meta Characters ....................................................................................................326 Grouping .................................................................................................................327 System ............................................................................................................................328 Random Number Generation ....................................................................................330 Dates and Times ...........................................................................................................331 Creating a New Time ............................................................................................332 Time Operations ....................................................................................................332 Creating a New Date .............................................................................................333 Date Operations ....................................................................................................333 Time Zone Information ........................................................................................335 Operating System Interface .......................................................................................336 System Information ..............................................................................................336 Process Management ...........................................................................................337 In Conclusion ................................................................................................................341 CHAPTER 12 The GUI — TkInter ...............................................................................343 What Is TkInter? ...........................................................................................................343 Terms and Conditions .................................................................................................343 Event Handling ......................................................................................................344 Callbacks .................................................................................................................344 Widgets ....................................................................................................................345 Layout Managers ...................................................................................................345 Working with TkInter .................................................................................................346 Creating a Label ...........................................................................................................347 Frame Widgets and Centering ..................................................................................349 An Application with a Button ...................................................................................351 Working with Entry Fields and Grid Layouts ........................................................353 Creating a Class to Handle User Interfaces ...........................................................356 Working with List Boxes ............................................................................................358 Scrolling a List Box ................................................................................................361 CONTENTS xiv Q Q Q Menus .............................................................................................................................363 Context Menus .............................................................................................................366 Scale Widgets ................................................................................................................367 RadioButtons and CheckButton ...............................................................................370 Text Widgets .................................................................................................................373 In Conclusion ................................................................................................................375 CHAPTER 13 The Web Server—Apache ...................................................................377 Setting Up Apache .......................................................................................................377 Testing Apache .............................................................................................................378 Your First Python CGI Script: Hello Apache ...........................................................379 Examining the Hello Python Script ...................................................................380 The cgi-bin Directory ............................................................................................381 A Script for Displaying the Environment ...............................................................382 Receiving Data from an HTML File ..........................................................................384 Sending Data to an HTML File ..................................................................................387 How It All Works ...................................................................................................390 Dynamic HTML Displays Based on User Input ......................................................391 HTML Elements ............................................................................................................396 Cookies ...........................................................................................................................399 Uploading Files ............................................................................................................402 Redirection ....................................................................................................................403 Error Handling ..............................................................................................................405 In Conclusion ................................................................................................................406 CHAPTER 14 Working with Databases ...................................................................407 What Is a Database? ...................................................................................................407 Simple Database Terminology ...........................................................................408 What Is MySQL? ...........................................................................................................409 Downloading and Installing ......................................................................................409 Creating a New Database ..........................................................................................410 Creating a New User ....................................................................................................414 CONTENTS xv Q Q Q Opening an Existing Database .................................................................................415 Writing to a Database ................................................................................................417 Reading from a Database ..........................................................................................421 Updating a Database ..................................................................................................424 Deleting from a Database ..........................................................................................427 Searching a Database .................................................................................................430 In Conclusion ................................................................................................................436 CHAPTER 15 Putting It All Together .......................................................................437 Designing the Application .........................................................................................437 Program Flow .........................................................................................................437 User Interface Design ...........................................................................................438 Database Design ...................................................................................................439 Implementing the Database Tables ........................................................................440 Implementing the Forms ...........................................................................................442 Adding Reviews ............................................................................................................449 Adding the Review to the Database ........................................................................452 Listing the Reviews ......................................................................................................456 Deleting Books .............................................................................................................459 In Conclusion ................................................................................................................462 CHAPTER 16 Python and Graphics ..........................................................................463 The PIL Library ..............................................................................................................463 Downloading ..........................................................................................................464 Installing .................................................................................................................464 Verifying Your Installation ..................................................................................465 Creating a New Image ................................................................................................465 Function Parameters ............................................................................................466 Drawing on the Image ................................................................................................467 Drawing the Image ...............................................................................................468 Displaying the Image ...........................................................................................470 CONTENTS xvi Q Q Q

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值