1 / 26

Data Structures and Algorithms

Data Structures and Algorithms. Second Year, First Semester, 2012/2013 List and String. List. A list is a sequential data structure, i.e. a collection of items accessible one after another beginning at the head and ending at the tail.

nickan
Download Presentation

Data Structures and Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structures and Algorithms Second Year, First Semester, 2012/2013 List and String

  2. List A list is a sequential data structure, i.e. a collection of items accessible one after another beginning at the head and ending at the tail. It is a widely used data structure for applications which do not need random access. It differs from the stack and queue data structures in that additions and removals can be made at any position in the list.

  3. It is used a one-dimensional array or 'vector' to store a list, each element of the array typically being a record containing data on an item. For example the following array, in 'C++', could store a list of students and their marks.

  4. Typedefstruct person { char name[21];int mark;} PERSON;PERSON student[100];

  5. The main primitive operations of a list are known as: • Add adds a new node • Set updates the contents of a node • Remove removes a node • Get returns the value at a specified index • IndexOfreturns the index in the list of a specified element

  6. Additional primitives can be defined: • IsEmptyreports whether the list is empty • IsFullreports whether the list is full • Initialisecreates/initialises the list • Destroy deletes the contents of the list (may be implemented by re-initialisingthe list)

  7. A constructor is required before a list can be used: • constructor List :: List( ); The List has been created and is initialized to be empty. The next operation takes a list that already exists and empties it: • void List :: clear( ); All List entries have been removed; the List is empty. Next come the operations for checking the status of a list: boolList :: empty( ) const; The function returns true or false according to whether the List is empty or not. • boolList :: full( ) const; The function returns true or false according to whether the List is full or not. • intList :: size( ) const; The function returns the number of entries in the List.

  8. The order of items stored in a list using an array is determined by the sequential positioning of the items in memory, ie consecutive items in the list are stored in consecutive memory locations. The use of a static array implies that the list will have a fixed maximum size determined by the variable declaration. This means that the maximum size must be determined in advance and the program written to allow for this even though it may frequently use only a small portion of the array. Alternatively space for a dynamic array can be calculated and allocated at runtime using malloc() before storing the items if the number of records is already known.

  9. A more important problem is met when one attempts to add an item to the list whilst preserving the order of the items. for example, to add the name BOB to the following list, it is necessary to copy each array element from student [3] onwards up one position in order to insert the new record. This problem will meet when studying the Insertion Sort algorithm. A similar problem exists when deleting records from the list.

  10. Initialise Creates the structure – i.e. ensures that the structure exists but contains no elements e.g. Initialise(L) creates a new empty queue Examples

  11. Example1 • Initialise L • Add e.g. Add(1,X,L) adds the value X to list L at position 1 (the start of the list is position 0), shifting subsequent elements up • Set e.g. Set(2,Z,L) updates the values at position 2 to be Z • Remove e.g. Remove(Z,L) removes the node with value Z • Get e.g. Get(2,L) returns the value of the third node, i.e. C • IndexOf e.g. IndexOf(X,L) returns the index of the node with value X, i.e. 1

  12. String Most languages either have a built in string datatype or a standard library, so rare to create own string ADT.

  13. A string datatype should have operations to: – Return the nth character in a string. – Set the nth character in a string to c++. – Find the length of a string. – Concatenate two strings. “Alison” + “ Cawsey” = “Alison Cawsey” – Copy a string. – Delete part of a string. (“Alison Cawsey” _ Alison”) – Modify and compare strings in other ways

  14. String Processing Algorithms The String processing algorithms are algorithms for processing sequences of characters or symbols e.g., – File compression - take a sequence, encode it as a shorter sequence. – Cryptography - take a sequence, encode it so enemies can’t read it! – String search - search for occurrences of one sequence within another. – Pattern matching - find out if sequence matches some pattern. – Parsing - Work out structure of a sequence, in terms of a grammar.

  15. Copy sequence of characters from string Copies a sequence of characters from the string content to the array pointed by s. This sequence of characters is made of the characters in the string that start at character position pos and span n characters from there. int main () { size_t length; char buffer[20]; string str ("Test string..."); length=str.copy(buffer,6,5); buffer[length]='\0'; cout << "buffer contains: " << buffer << "\n"; return 0; }

  16. String comparison Compares the content of this object (or a substring of it, known as compared (sub)string) to the content of a comparing string, which is formed according to the arguments passed.The member function returns 0 if all the characters in the compared contents compare equal, a negative value if the first character that does not match compares to less in the object than in the comparing string, and a positive value in the opposite case.Notice that for string objects, the result of a character comparison depends only on its character code (i.e., its ASCII code), so the result has some limited alphabetical or numerical ordering meaning.

  17. int main (){ string str1 ("green apple"); string str2 ("red apple");  if (str1.compare(str2) != 0) cout << str1 << " is not " << str2 << "\n";  if (str1.compare(6,5,"apple") == 0) cout << "still, " << str1 << " is an apple\n";  if (str2.compare(str2.size()-5,5,"apple") == 0) cout << "and " << str2 << " is also an apple\n";  if (str1.compare(6,5,str2,4,5) == 0) cout << "therefore, both are apples\n";  return 0; }

  18. String Matching String matching is fundamental to database and text processing applications. Every text editor must contain a mechanism to search the current document for arbitrary strings. Example: -Match a word study • Str1 (input) = You will always have a study, my study, for the study the study is studying as study itself. • Str2 (output) = The matching words are:

  19. Clear string The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters. int main (){ string str; charc; cout << "Please type some lines of text. Enter a period to finish:\n"; do { c=cin.get(); str += c; if (c=='\n') { cout << str; str.clear(); } } while (c!='.'); return 0; }

  20. String length Returns a count of the number of characters in the string. int main (){ string str ("Test string"); cout<< "The length of str is " << str.length() << " characters.\n"; return0; }

  21. Get C string equivalent Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.A terminating null character is automatically appended. int main (){ char * cstr, *p;  string str ("Please split this phrase into tokens");  cstr= newchar [str.size()+1]; strcpy(cstr, str.c_str());  // cstr now contains a c-string copy of str  p=strtok (cstr," "); while(p!=NULL) { cout << p << endl; p=strtok(NULL," "); }  delete[] cstr; return 0;}

  22. Swap contents with another string Swaps the contents of the string with those of string object str, such that after the call to this member function, the contents of this string are those which were in str before the call, and the contents of str are those which were in this string. main (){ string buyer ("money"); string seller ("goods");  cout << "Before swap, buyer has " << buyer; cout<< " and seller has " << seller << endl;  seller.swap (buyer);  cout<< " After swap, buyer has " << buyer; cout << " and seller has " << seller << endl;  return 0; }

  23. Insert into string The current string content is extended by inserting some additional content at a specific location within the string content (this position is determined by either pos1 or p, depending on the function version used). int main (){ string str="to be question"; string str2="the "; string str3="or not to be"; string::iterator it;  // used in the same order as described above:str.insert(6,str2); // to be (the )question str.insert(6,str3,3,4); // to be (not )the question str.insert(10,"that is cool",8); // to be not (that is )the question str.insert(10,"to be "); // to be not (to be )that is the question str.insert(15,1,':'); // to be not to be(:) that is the question It=str.insert(str.begin()+5,','); // to be(,) not to be: that is the question str.insert(str.end(),3,'.'); // to be, not to be: that is the question(...) str.insert(it+2,str3.begin(),str3.begin()+3); // (or ) cout << str << endl; return 0;}

  24. What are the output of the following c++ code? #include <iostream.h> #include <cstring.h> void main() { string s2 = "string"; string s3 = "this"; cout << s2.length()<< s2+s3 << endl; s3 += s2; s3.insert(4, " is a "); cout << s3; int x = strlen(s2); s3.replace(0, 4, "that"); cout << s3; }

  25. The end Any question?

More Related