4.1 Ordered Lists Revisited

Size: px
Start display at page:

Download "4.1 Ordered Lists Revisited"

Transcription

1 Chapter 4 Linked-lists 4.1 Ordered Lists Revisited Let us revisit our ordered-list. Let us assume that we use it for storing roll numbers of students in a class in ascending order. We can make the assumption that these roll numbers are of type integer. Assuming a class size of 50, we can create an object of OrderedList as follows: OrderedList <int> class1(50); Everything looks fine except the fact that in practice class sizes are quite variable we can have classes of sizes ranging from less than 10 to classes having a few hundred students. The problem is that if we allocated memory for the maximum possible class size then we would be wasting a lot of space for the usual cases. On the other hand if we did not do that then our program would not be able to handle large classes. We could overcome this difficulty by dynamically reallocating memory if it was determined at run time that more space was needed 1. Accordingly we rewrite the insert method (Fig ) void OrderedList <class T>:: insert(t value) if (isfull() ) resize(); // insert value in the list void OrderedList <class T>:: resize(float inc = 10.0) MaxSize = MaxSize*(1 + inc/100); T * temp = new T[MaxSize]; if (temp == ) raise OUT_OF_MEMORY; for (int i = 0; i < msize; i++) temp[i] = ListArray[i]; delete []ListArray; ListArray = temp; As can be seen easily, the resize method achieves its objective in O(N). However, we now have a system in which the required space grows dynamically according to the need. 1 C++ template class vector does something similar

2 Chapter 4 Linked-Lists Page 2 of 37 This system nevertheless suffers from the problem of a lot of data movement. The function resize involves significant amount of data movement and for complex data types it could be a very heavy and time consuming operation. The same is true for insert, remove, and change operations as well. On the average, these operations require shifting n/2 elements from their original location to a new position. The overall time complexity of these operations remains O(n) but the data movement makes them very inefficient if large amounts of data is involved. When we deal with linear or ordered-lists, it is in general not required to have a random access to the elements. e.g., we usually do not need to ask questions like: who is the 8th person in this class? The data is usually processed in a strictly sequential order. Therefore we only need a mechanism to access the next element. If we can somehow tell where the next element is stored, we can eliminate this restriction of placing the next element at the next physical location. This gives rise to the notion of logical adjacency as opposed to physical adjacency. In that case, in order to access elements of a list, all we need is a starting point and some means to move from one element to the next. In other words, we need a starting point and a link from one element to the next. This observation can be used to avoid movement of data in the case of insert, remove, and change operations by just maintaining logical adjacency of elements instead of requiring them to be physically adjacent as well. The order of the sequence can be maintained by simply recording where the next element in the sequence is physically present. This results in a chain like structure where we can access the elements in the chain by just following the links in the chain. Such an organization is known as a linked-list. A detailed discussion on linked-lists follows. 4.2 Implementing Linked-Lists Linked-list can be implemented in an array (exercise # ) but it is much easier to implement a linked-list with the help of pointers and dynamic memory allocation.

3 Chapter 4 Linked-Lists Page 3 of 37 We first define a node with two components: (1) a place for storing data, and (2) a pointer to the next node in the chain. This arrangement is shown in Figure struct Node T data; Node<T> * next; ; Data Next Depiction of a Node Structure A linked-list is now defined as a chain of linked nodes with a pointer pointing to the first or node in the chain. Specification of LinkedList in C++ is given in Figure. template<class T> class LinkedList friend class LinkedListIterator<T>; // iterator public: LinkedList(); // constructor ~ LinkedList (); // destructor void insert(t value); void remove (T value); LinkedList(const LinkedList & ol); // copy constructor const LinkedList & operator=(const LinkedList & rhs); // assignment operator private: Node <T> * ; ; An abstract depiction of a linked list with 5 nodes is presented in Fig The following points are worth noting down: 1. The pointer points to the first node in the list. 2. The end of the list is indicated by putting in the next field of the last node. 3. We can only move in the direction of the link. That is, we can move from a node to the node next to it but we cannot go back to the previous node.

4 Chapter 4 Linked-Lists Page 4 of 37 Let us now define and discuss at each method of the LinkedList abstract data type The constructor The constructor simply initializes the pointer to be equal to to indicate an initially empty list. LinkedList<T>::LinkedList() = ; List traversal and the Iterator As discussed in the last chapter, we would need iterators to iterate over the elements of the linked-list class so that we can process data according to our own specific needs without exposing the internal implementation details of the underlying collection class and is shown in Figure class LinkedListIterator private: LinkedList<T> *list; Node<T> *current; public: LinkedListIterator( LinkedList<T> *ll): list(ll), current(ll->) void begin()current = list->; bool isdone() return current == ; void next() if (!isdone()) current = current->next; else throw ILLEGAL_REFERNCE_EXCEPTION; T getdata() if (!isdone()) return current->data; else throw ILLEGAL_REFERNCE_EXCEPTION; ;

5 Chapter 4 Linked-Lists Page 5 of 37 We can now use this iterator to process information stored in the linedlist as shown in Figure LinkedList<int> intlist; // add data to the list LinkedListIterator<int> myiterator(&intlist); // create iterator and attach list to it for(myiterator.begin();!myiterator.isdone(); myiterator.next()) cout << myiterator.getdata() << " "; Inserting and deleting a node after a given node Insertion and deletion are the two fundamental operations for any container class. Before discussing insertion and deletion in general, let us define the following two methods (not shown in class specification): (a) insert an element after a given node, and (b) delete the node after a given node. These two functions will help us in understanding a number of concepts involved in implementing linked-lists. Insertion after a given node The code for inserting for inserting a new element in the linked-list after a given node is given below: void LinkedList<T>:: addafter(node<t> * current, T data) Node <T> *newelement = new Node<T>; if (newelement == ) throw OUT_OF_MEMORY; newelement->data = data; newelement->next = current->next; current->next = newelement; Let us try to understand the different steps involved in this operation with the help of a simple example. Let us assume that we start with the linkedlist of Fig and insert 6 after node with data value 5. The operation involves the following three basic steps: 1. Create a new node and store data in it. a. Create a new node by dynamically allocating memory and check if memory has been properly allocated. It is very important to

6 Chapter 4 Linked-Lists Page 6 of 37 always check for value after dynamically allocating memory. Failing to do so could cause a run-time error and could result in corrupting data or crashing the system. b. Set the data part of the newly created node to be equal to the input data. This step is depicted in Figure current newelement 6 Step 1 creating a new node and setting its data component newelement = new Node<T>; If (newelement == ) throw OUT_OF_MEMORY; newelement->data = data; 2. Set the next field in the newelement to point to the node pointed to by the current node. Following figure contains the same mistake current newelement 6 Step 2: make the newelement point to the node pointed to by current newelement = current->next; 3. We complete operation by severing the link of current node to its next node and making it point to the newelement. This step is depicted below current newelement 6 Step 3: adjust the link in the node pointed to by current Current->next = newelement;

7 Chapter 4 Linked-Lists Page 7 of 37 It is easy to see that if we now traversed the list from start, we would go to 6 from 5 and then to 8. The important thing to note is that we have achieved data insertion without any data movement as was the case when the ordered list was implemented in an array. Another point to remember is that we can only add after a node and not before it as the link points to the next element and there is no way to go back to the previous element without going back to the start of the list and then traversing it again from the very beginning. Checking for the boundary condition - inserting after the last node It may also be noted that this would work properly even if next of current was. That is, current was the last node in the list and we wanted to add a node at the end of the list. We would however need to ensure that current is not and hence the code is updated accordingly: void LinkedList<T>:: addafter(node<t> * current, T data) Node <T> *newelement = new Node<T>; if (current!=) if (newelement == ) throw OUT_OF_MEMORY; newelement->data = data; newelement->next = current->next; current->next = newelement; Warning Fragile: Handle with care It is very important that we take extreme care while dealing with pointers and linked-lists as a single mistake may result in losing a lot of data without any possibility of recovering it. Let us discuss why. Let us assume that we swap the last two statements of the addafter function resulting in the following incorrect function:

8 Chapter 4 Linked-Lists Page 8 of 37 void LinkedList<T>:: addafter(node<t> * current, T data) // incorrect version Node <T> *newelement = new Node<T>; if (newelement == ) throw OUT_OF_MEMORY; newelement->data = data; current->next = newelement; newelement->next = current->next; The chaotic situation created by this seemingly minor mistake is elaborated in Figure current new Element 7 Statement#4 Current->next = newelement; This part is no longer accessible current newelement 7 Statement#5 newelement->next = current->next;

9 Chapter 4 Linked-Lists Page 9 of 37 Deleting a node next to a given node Let us now look at the initial version of the code to delete the node after a given node, the second of the two private methods mentioned above. void LinkedList<T>:: deleteafter(node<t> * current) // incorrect version Node<T> *temp; temp = current->next; current->next = current->next->next; // same as // current->next = temp->next; delete temp; The node to be deleted is delinked (or skipped) from the list by making next field of the node pointed to by current to point to the node after the targeted node and then delete this node. Once again there are three steps elaborated next. 1. Make temp point to the node to be deleted. Since we need to remember the node to be deleted, therefore we store the address of this node in a temporary variable. This address will be used later in step Step#1 temp = current->next; current temp 2. Skip the targeted node by making the node pointed to by current point to the node after the targeted one.

10 Chapter 4 Linked-Lists Page 10 of Step#2 current->next = current->next->next; current temp This element is no longer accessible 3. The targeted node is finally deleted by sending the memory back to the operating system. Remember that failing to do so would result in memory leak. û Step#3 delete temp; current temp Once again it is important to perform these steps in the right order. For example, performing step 3 before step 2 would result in illegal memory access. The boundary condition current points to the last node in the list What happens if the pointer passed to this function points to the last node in the list? In that particular case current->next is and hence current->next->next is an invalid operation. We must therefore ensure to check for this condition before proceeding to delete the node. Like the addafter function, we also need to ensure that current is not. Accordingly, the modified (and correct) deleteafter function is written next:

11 Chapter 4 Linked-Lists Page 11 of 37 void LinkedList<T>:: deleteafter(node<t> * current) // correct version if (current!= ) Node<T> *temp; temp = current->next; if (temp!= ) current->next = current->next->next; // same as // current->next = temp->next; delete temp; Note that in this particular case we have decided not to do anything if current is or points to the last node. If required, we could also indicate an error by throwing an exception or sending an error code back Searching data in the list The search operation (Figure ) simply requires traversing the list till the node containing the key is found. bool LinkedList<T>::search(T key) Node<T> *current = ; while (current!= && current->data!= key) current = current->next; if (current!= ) return true; else return false; The code is quite simple. However there are two very important points to be remembered: 1. Condition in the while loop needs to be very carefully written. Note that the statement (current!= && current->data < data) is not the same as (current->data < data && current!= ).

12 Chapter 4 Linked-Lists Page 12 of 37 In the first case, because of short-circuiting current->data will not be evaluated if current is. On the other hand, in the second case, since we access data before checking the value of current, the program will most probably crash when current becomes. 2. Linked-lists do not provide random access to nodes if a nodes needs to be accessed, it must be reached sequentially, starting from the first node. That means, even if the data was stored in ascending or descending order, we could not use something like binary search Insertion into a linked-list Let us assume that our linked-list is used to store data in ascending order. Inserting an element would then require inserting it at its right place so that the required order is maintained. We would need to perform the following 3 steps: 3. Allocate memory for the new node 4. Find the right position for insertion of data. 5. Insert the new node In addition, for the proper working of the function, we would need to identify boundary conditions and ensure that the code works for those conditions. The code is presented in Fig

13 Chapter 4 Linked-Lists Page 13 of 37 void LinkedList<T>::add(T data) Node<T> *temp = new Node<T>;// allocate space for the new node if (temp == ) throw OUT_OF_MEMORY; else temp->data = data; Node<T> *current, *previous; // starting with the first node, find the right // position for inserting data current = ; while (current!= && current->data < data) previous = current; current = current->next; // previous and current point to the nodes which would // be after and before the new node respectively. temp -> next = current; // check for boundary condition // if data is to be inserted before the first node // then the pointer also needs to be adjusted if (current == ) = temp; else previous->next = temp; Following points need special attention: 1. As we have already seen, we cannot add before a given node. We would therefore need to position at a node after which the new node would be inserted. For that purpose we would need to maintain two pointers one pointing to the current node and the other one pointing to the node previous to the current node. That is, in general, the new node would be inserted between the node pointed to by previous and current. 2. There are four different cases to be considered: a. Adding the first element in the initially empty list. b. Adding an element before the first element in the list. c. Adding after the last element in the list.

14 Chapter 4 Linked-Lists Page 14 of 37 d. The general case adding an element between two elements in the list. In the first two cases (a and b), since a new node is added to the of the list, the needs to be updated so that its points to this new node. In both these cases, the control comes out of the for loop with current equal to ( if list is empty is also in that case) with previous yet to be assigned a value. Careful analysis of the code shows that no special treatment is required for case c. The code along with the four cases mentioned above is explained with the help of Figure

15 Chapter 4 Linked-Lists Page 15 of 37 x x is the data to be inserted. A new node is created and is pointed to by temp. x is stored in the data field of temp. temp Case#1: initially empty list Loop terminates with: current equal to which is previous is not assigned any value yet temp->next = current; sets temp->next to be equal to if ( == current) = temp; sets the new value of to point to the new node which would be the first node in the list. At the end we will have the following situation: x Case#2: list is not empty and data is inserted before the first node, that is x is smaller than data stored in the first node current Loop terminates with: current is equal to which points to the first node in the list previous is not assigned any value yet temp->next = current; sets next of temp to point to the first node in the list if ( == current) = temp; sets the new value of to point to the new node which would be the first node in the list. At the end we will have the following situation: x

16 Chapter 4 Linked-Lists Page 16 of 37 Case#3: list is not empty and data is inserted after the last node, that is x is greater than all the data stored in the list Loop terminates with: current equal to that is it is after the last node in the list previous points to the last node in the list temp->next = current; sets next of temp to previous->next = temp; sets next of the last node to point to the new node. At the end we will have the following situation: previous current x Case#4: General case - list is not empty and data is inserted somewhere in the middle previous current Loop terminates with: previous points to the node after which the new node is to be inserted and current points to the node before which it is to be inserted. temp->next = current; sets next of temp to current or the node after previous previous->next = temp; sets next of previous to point to the new node. At the end we will have the following situation: x

17 Chapter 4 Linked-Lists Page 17 of Removing a node from the linked-list Deleting an element would first require that we locate the node which has the key and then remove it from the list. void LinkedList<T>::remove(T key) Node<T> *current, *previous; current = ; while (current!= && current->data!= data) previous = current; current = current->next if (current!= ) if (current == ) = -> next; else previous->next = current->next; delete current; As we have already seen, in order to delete a node, we need the pointer to the node before it. Therefore, just like addition, we would need to maintain two pointers one pointing to the current node and the other one pointing to the node previous to the current node. That is, in general, the node to be deleted would be the one after the node which is pointed to by previous. When the loop terminates, there are two cases: 1. Key is not found in this case current will be equal to. Nothing needs to be done in that case. 2. Key is found in this case current points to the node to be deleted. We now have two cases to consider: a. The node to be deleted is the first node in the list. That means (i) previous will not have any value assigned to it, and (ii) after deletion is complete, should point to the node which was next to the previously first node in the list (or to if the node removed was the only node in the list). The general case where the node to be deleted is not the first node and hence previous will be pointing to the node before the node to be

18 Chapter 4 Linked-Lists Page 18 of 37 deleted. In this case we simply make next of previous point to next of current and delete the node pointed to by current.following figure contains mistakethese two scenarios are depicted in Figure.. or if there is only one node in the list Case 2a: Node to be deleted is the first node in the list current Loop terminates with: current is equal to which points to the first node in the list previous is not assigned any value yet Head = ->next sets to point to the node after the first node (or if there is only one node in the the only node in the list) Delete current deletes the first node At the end we will have the following situation: Case 2b: The general case previous current Loop terminates with: previous points to the node after which node is to be deleted and current points to the node to be deleted. previous->next = current->next sets next of previous to point to node after current (or if current is the last node in the list) delete current deletes the node pointed to by current. At the end we will have the following situation:

19 Chapter 4 Linked-Lists Page 19 of The destructor As the linked-list is using dynamically allocated memory, we must write the destructor for the class. The destructor needs to sequentially traverse all the nodes in the list and then delete them one by one. It is important to remember that we cannot delete a node and then try to access the node next to it by using the pointer of the next node stored in the next field of the node that has been deleted. As soon as a node is deleted, a pointer pointing to it becomes a dangling pointer and it is illegal to use a dangling pointer to access any part of the deleted node. Therefore, we must store the address of the next node before deleting a node. LinkedList<T>::~LinkedList() Node<T> *temp1, *temp2; temp1 = ; while (temp1!= ) temp2 = temp1->next; delete temp1; temp1 = temp2; 4.3 Using iterator to define a sort-order on the data stored in the linked-list The linked-list class described in the previous section does not associate any order to the data stored in it. For example, the class does not directly provide any facility to store data in ascending order. The primary objective of the linked-list class is to provide a mechanism to store data as a linear list without including data/application specific operations, including sort-order of the data. In fact it is not desirable to provide mechanism to support all kinds of sort-orders inside the linked-list class as these would be very specific to the given application. Such application specific operations can be built with the help of the iterator. For example, we can write an iterator that can be used to specify the order in which the data is to be maintained by the linked-list and the iterator implementation

20 Chapter 4 Linked-Lists Page 20 of 37 given in Figure can be used maintain data in the linked-list ascending order. To support insertion of data in ascending order, the iterator implementation given in section is modified to maintain a pointer to the node before the current node and two list manipulation methods namely insert and remove to insert and remove data from the linked-list and maintain the required order.

21 Chapter 4 Linked-Lists Page 21 of 37 class LinkedList friend UpdatedListIterator<T>; // rest is the same private: void insertafter(t data, Node<T> *p); void removeafter(node<t> *p); void insertfirst(t data); void removefirst(); Node<T> *; ; class UpdatedListIterator private: LinkedList<T> *list; Node<T> *current, *previous; public: UpdatedListIterator(const LinkedList<T> *ll): list(ll), current(ll->), previous() void begin() current = list->; previous = ; bool isdone() return current == ; void next() if (!isdone()) previous = current; current = current->next; else throw ILLEGAL_REFERNCE_EXCEPTION; T getdata() if (!isdone()) return current->data; else throw ILLEGAL_REFERNCE_EXCEPTION; void insert(t data) for (begin();!isdone() && data > getdata(); next()); if (previous == ) list->insertfirst(data); begin(); else list->insertafter(previous, data); current = previous->next;

22 Chapter 4 Linked-Lists Page 22 of 37 void remove(t data) for (begin();!isdone() && data > getdata(); next()); ; if (!isdone() && data == getdata()) if (previous == ) list->removefirst(); begin(); else list->removeafter(previous); current = previous->next; This concept can be extended for more leverage and flexibility. For example, the iterator implementation can be modified so that, instead of insert and remove, we provide three list manipulation methods namely insertaftercurrent, insertbeforecurrent, and removecurrent to perform the operations suggested by the method names. Figure shows implementation of these methods. void insertaftercurrent(t data) if (!isdone()) list->insertafter(current, data); current = previous->next; else throw ILLEGAL_REFERNCE_EXCEPTION; void insertbeforecurrent(t data) if (previous == ) list->insertfirst(data); begin(); else list->insertafter(previous, data); current = previous->next; void removecurrent() if (!isdone()) if (previous == ) list->removefirst(); begin(); else list->removeafter(previous); current = previous->next; else throw ILLEGAL_REFERNCE_EXCEPTION;

23 Chapter 4 Linked-Lists Page 23 of 37 This provides greater flexibility and control to the client program. For example, as shown below, this iterator can now be used to insert data in descending order. void insertdescending(t &data, UpdatedListIterator<T> &li) for(li.begin();!li.isdone() && data > li.getdata();li.next()); li.insertbeforecurrent(data);

24 Chapter 4 Linked-Lists Page 24 of Using linked-lists to implement stacks and queues As stack and queue are linear data structures where random access of elements stored in these data structures is not required, they can be very easily implemented by using linked-lists Implementing stack Implementation of stacks with linked-lists is a straight forward exercise. We can very easily add and delete a node to and from the front of the list in O(1). So we treat the pointer as the stack pointer and then implement push and pop operations. Since we are using dynamically allocated memory, theoretically speaking, the stack will never be full. Therefore it will always return false. Figure shows linked-list implementation of stack. class Stack public: Stack() stkptr = ; // constructor ~Stack(); // destructor void push (const T &); // add an element to the stack T pop( ); // remove an element from stack bool isfull() return false; // check if the stack is full bool isempty()return stkptr == ; // check if the stack is empty private: Node<T> *stkptr; // stack pointer Stack(const Stack &other); // disallow copy Stack& operator =(const Stack& other); // disallow assignment ; void Stack<T>::push(const T &data) Node<T> *temp = new Node; if (temp == ) throw OUT_OF_MEMORY; else temp->data = data; temp->next = stkptr; stkptr = temp; T Stack<T>::pop() T data; Node<T> *temp = stkptr; if (isempty()) throw STACK_EMPTY; else data = temp->data; stkptr = stkptr->next; delete temp; return data;

25 Chapter 4 Linked-Lists Page 25 of Implementing queue As opposed to stack, in queues additions and deletions are carried out at two different ends. We would therefore need to maintain information about the first and last node in the list. As depicted in Fig, this can be very easily done by keeping pointers to the first and last nodes in the list. The only questions to be answered are: 1. Can we add and remove in O(1) from two different ends of a linked list? 2. Which end should be designated as front and which should be used as rear? So, given a linked-list with two pointers pointing to the first and last nodes in the list, we ask the following questions: 1. Can we add before the first node in O(1)? 2. Can we add after the last node in O(1)? 3. Can we delete the first node in O(1)? 4. Can we delete the last node in O(1)? As we have already seen in the case of stack, the answers to the first and third questions are yes. The answer to the second question once again is yes. How? Let us see. Let us assume that we have the following linked-list with pointers to the first and last node in the list first last if t points to the new node to be inserted at the end, we can achieve that as follows: last->next = t; t->next = ; last = t;

26 Chapter 4 Linked-Lists Page 26 of 37 The answer to the fourth question is no because after deleting the last node in the list, the pointer pointing to the last node must be readjusted to point to the one before that. Since we cannot go back to the previous node in O(1), we cannot therefore perform this operation in O(1). In short, we can add or delete to and from the first node in O(1) but the only add in O(1) at the last node. Since, in the queue, we add at the rear and delete from the front, rear has to point to the last node and front points to the first node in the list. Once that is decided, the rest is easy except that there are two special cases. That is, we need to adjust the rear and front pointers when the last node is deleted from the queue or the first node is added to the queue. Figure class Queue public: Queue() front = rear = ; // constructor ~Queue(); // destructor void add (const T &); // add an element to the stack T remove( ); // remove an element from stack bool isfull() return false; // check if the stack is full bool isempty()return front == ; // check if the stack is empty private: Node<T> *front, *rear; // stack pointer Queue(const Queue &other); // disallow copy Queue& operator =(const Queue& other); // disallow assignment ; void Queue<T>::add(const T &data) Node<T> *temp = new Node; if (temp == ) throw OUT_OF_MEMORY; else temp->data = data; temp->next = ; if (rear = ) rear = front = temp; else rear->next = temp; rear = temp; T Queue<T>::remove() T data; Node<T> *temp = front; if (isempty()) throw STACK_EMPTY; else data = temp->data; front = front->next; delete temp; if (front == ) rear = ; return data;

27 Chapter 4 Linked-Lists Page 27 of Revisiting Linked-Lists implementation using dummy node to eliminate special cases In the methods for adding and removing nodes from the linked-lists, we needed to write extra code to take care of two boundary conditions adding before the first node and removing the first node. In both these cases the pointer needed to be readjusted to point to the new node in the linked-list. In both these cases the loop terminated without assigning any value to previous pointer. We can avoid this situation if we can ensure that the first node is permanent it is added at the initialization time and is never deleted and we ensure that nothing ever comes before this node. That is, we can add a dummy node at the start of the list, or alternatively, itself could be a node instead a pointer. We rewrite the linked list operations accordingly. template<class T> class LinkedList public: // list of public methods private: Node <T> *; ; LinkedList<T>::LinkedList() = new Node<T>; if ( == ) throw OUT_OF_MEMORY; ->next = ; void LinkedList<T>::remove(T key) Node<T> *current, *previous; previous = ; current = ->next; while (current!= && current->data!= data) previous = current; current = current->next if (current!= ) previous->next = current->next; delete current;

28 Chapter 4 Linked-Lists Page 28 of 37 void LinkedList<T>::add(T data) Node<T> *temp = new Node<T>; if (temp == ) throw OUT_OF_MEMORY; else temp->data = data; Node<T> *current, *previous; previous = ; current = ->next; while (current!= && current->data < data) previous = current; current = current->next; temp -> next = current; previous->next = temp; In these cases current is initialized to next of and previous gets an initial value of address of. That ensures that when the loop terminates, previous is never unassigned. We then insert and remove the node after previous just like any general case, thus eliminating both special cases. Initially empty list with a dummy mode List with dummy node

29 Chapter 4 Linked-Lists Page 29 of 37 Insertion before the first node Deleting the first node

30 Chapter 4 Linked-Lists Page 30 of Circular lists In many situations a circular structure is more suitable as compared to a linear structure. For example, it would be easier and natural to process information about a polygon if its corners were stored in a circular structure. Similarly, round-robin queues are better organized as circular entities. Such organizations, known as circular lists, can be achieved vey easily by linking the last and first node of the list together. That is, by replacing the in the next field of the last node by the address of the first node of the list. One big advantage of a circular list is that each node of the list can be reached from every other node (in O(N)). Traversal of the list can start from any node and ends when the start node is reached again. Viewed another way, a circular linked-list has no designated start or end nodes and pointer to any node can serve as the starting point. It is much easier to implement a circular list if, instead of the first node, pointer to the last node (also called the tail) is maintained. The tail pointer provides access to both the last and first nodes in the list in O(1). It is also helpful in applications like queue where access to both ends of the list is required. Circular lists can be implemented with or without the dummy /tail node. Partial implementation of the list with a pointer to tail is given in Figure. Because all nodes of the list are connected with one another and traversal can start from any node, iteration becomes a little complex and requires handling of some special cases. There is also a danger of ending up in an infinite loop if code is not written carefully.

31 Chapter 4 Linked-Lists Page 31 of 37 template<class T> class CircularList public: CircularList(); // constructor ~ CircularList (); // destructor void insert(t value); void remove (T value); bool search(t key); void print(); CircularList(const CircularList & ol); // copy constructor const CircularList & operator=(const CircularList & rhs); // assignment operator private: Node <T> * tail; // maintain pointer to the last node ; CircularList<T>::CircularList() tail = ; bool CircularList<T>::search(T key) Node<T> *current = tail->next; while (current!= tail && current->data!= key) current = current->next; if (current->data == key) return true; else return false;

32 Chapter 4 Linked-Lists Page 32 of 37 tail An empty circular list 5 Circular list with only one node tail A circular list in general void CircularList<T>::insert(T data) Node<T> *temp = new Node<T>;// allocate space for the new node if (temp == ) throw OUT_OF_MEMORY; else temp->data = data; Node<T> *current, *previous; tail if (tail == ) // adding first node in the list tail = temp; temp->next = tail; else current = tail->next; previous = tail; while (current!= tail && current->data < data) previous = current; current = current->next; if (current == tail && current->data < data) // adding after tail // hence getting a new tail temp->next = current->next; current->next = temp; tail = temp; else // general case temp->next = current; previous->next = temp;

33 Chapter 4 Linked-Lists Page 33 of Doubly linked lists Sometimes it is important to be able to go back and forth from a given point in the list. This can be accomplished by simply adding a pointer to the previous node as well. Such a list is called doubly-linked-list. struct DLLNode T data; Node<T> * next; Node<T> * previous; ; Once again, a doubly linked-list can be implemented with or without a dummy node. Class specification for a doubly linked-list with dummy node is given in Fig.. template<class T> class DoublyLinkedList public: // list of public methods private: DLLNode <T> ; ; DoublyLinkedList <T>:: DoublyLinkedList ().next = &;.previous = &;

34 Chapter 4 Linked-Lists Page 34 of 37 In a doubly linked list, for any node pointed to by p, we have the following: p == p->next->previous p == p->previous->next Given a pointer to any node, we use this property to add/remove the node itself or the node before or after it in O(1). Figure shows code segments for inserting a node before a node pointed to by current and deleting the node pointed to by current. p->previous = current->previous; p->next=current; p->next->previous = p; // same as current->next->previous = p; p->previous->next = p; deleting a node pointed to by p current->previous->next = current->next; current->next ->previous = current->previous; delete current; Inserting before the current node

35 Chapter 4 Linked-Lists Page 35 of 37 Deleting the node pointed to by current

36 Chapter 4 Linked-Lists Page 36 of Tradeoffs and Comparison Like any field and application, no method of implementing lists is well suited to all situations there are tradeoffs that one needs to be aware of. Following is a comparison of different data structures discussed so far Linked-lists versus arrays In general, the main advantage of arrays over linked list is that arrays allow random access to any element in O(1) and whereas linked-lists allow only sequential access. Hence, in an array search can be performed on sorted data in O(log n) whereas it takes O(n) in the case of a linkedlist. In almost all other cases linked-list is a better choice. The following tables summarize tradeoffs between arrays and linked-lists: Array Linked-list Indexing O(1) O(n) Insert/delete at end O(1) O(1) Insert/delete at start O(n) O(1) Insert/delete in the middle O(n) O(1) (insertion point given) Locality (affects cache hit ratio) great poor Size limitations Yes no (for fixed arrays) Resizing expensive built-in memory wastage yes no extra storage needed for storing no yes addresses allocation/deallocation for each no yes element tail sharing no yes (singly-linkedlist) only

37 Chapter 4 Linked-Lists Page 37 of Doubly-linked vs. singly-linked As compared to singly linked-lists, doubly linked-list requires extra memory to store an additional pointer and the basic operations (add/delete) are relatively more expensive. However, since it allows sequential access in both directions, doubly-linked-lists are easier to manipulate. Table summarizes the differences between singly and doubly linked lists. Singly linked-list Extra storage needed for storing addresses insert/delete operations insert/delete current node access in both directions No Yes Allow tail sharing Yes No doubly linked list more more expensive easier Circularly-linked vs. linearly-linked Circular linked lists allow traversal of the entire list starting from any given point in the list. Hence they are advantageous in describing naturally circular structures. Their main disadvantage lies in more complex basic operations with special cases. Table summarizes these differences. Linear Not directly Circular yes Represent circular structures Traverse entire list No yes starting at any point special cases more access to first node O(1) O(1) access to last node O(n) O(n) allow tail sharing Yes No

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE Chapter 1 : What is an application of linear linked list data structures? - Quora A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Ashish Gupta, Data JUET, Guna

Ashish Gupta, Data JUET, Guna Categories of data structures Data structures are categories in two classes 1. Linear data structure: - organized into sequential fashion - elements are attached one after another - easy to implement because

More information

Linked lists (6.5, 16)

Linked lists (6.5, 16) Linked lists (6.5, 16) Linked lists Inserting and removing elements in the middle of a dynamic array takes O(n) time (though inserting at the end takes O(1) time) (and you can also delete from the middle

More information

3.1 Arrays Representation and basic operations

3.1 Arrays Representation and basic operations Chapter 3 Arrays and Vectors 3.1 Arrays Representation and basic operations Array is a very basic and one of the simplest and most widely used data structure provided by every programming language. In

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

More information

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays Unit 3: Linked Lists Part 2: More on Linked Lists 1 Deletion in singly linked lists (cont d) 1 Other Functions Engineering 4892: Data Structures 1 Doubly Linked Lists Faculty of Engineering & Applied Science

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

CE204 Data Structures and Algorithms Part 2

CE204 Data Structures and Algorithms Part 2 CE204 Data Structures and Algorithms Part 2 14/01/2018 CE204 Part 2 1 Abstract Data Types 1 An abstract data type is a type that may be specified completely without the use of any programming language.

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

CMSC 341 Lecture 7 Lists

CMSC 341 Lecture 7 Lists CMSC 341 Lecture 7 Lists Today s Topics Linked Lists vs Arrays Nodes Using Linked Lists Supporting Actors (member variables) Overview Creation Traversal Deletion UMBC CMSC 341 Lists 2 Linked Lists vs Arrays

More information

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues By: Pramod Parajuli, Department of Computer Science, St. Xavier

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Intro to Data Structures Vectors Linked Lists Queues Stacks C++ has some built-in methods of storing compound data in useful ways, like arrays and structs.

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked list variations, allow insertion and deletion

More information

Questions: ECE551 PRACTICE Final

Questions: ECE551 PRACTICE Final ECE551 PRACTICE Final This is a full length practice midterm exam. If you want to take it at exam pace, give yourself 175 minutes to take the entire test. Just like the real exam, each question has a point

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Introduction to Linked Lists Stacks and Queues using Linked Lists Next Time Iterative Algorithms on Linked Lists Reading:

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked List. April 2, 2007 Programming and Data Structure 1 Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element

More information

Introduction to Linked Lists

Introduction to Linked Lists Introduction to Linked Lists In your previous programming course, you organized and processed data items sequentially using an array (or possibly an arraylist, or a vector). You probably performed several

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

More information

Cpt S 122 Data Structures. Data Structures

Cpt S 122 Data Structures. Data Structures Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation

More information

CS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial

CS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial Week 7 General remarks Arrays, lists, pointers and 1 2 3 We conclude elementary data structures by discussing and implementing arrays, lists, and trees. Background information on pointers is provided (for

More information

ITI Introduction to Computing II

ITI Introduction to Computing II index.pdf March 17, 2013 1 ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 17, 2013 Definitions A List is a linear abstract

More information

Queue Definition. Ordered list with property:

Queue Definition. Ordered list with property: Queue Definition Ordered list with property: All insertions take place at one end (tail) All deletions take place at other end (head) Queue: Q = (a 0, a 1,, a n-1 ) a0 is the front element, a n-1 is the

More information

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19 Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2008 7p-9p, Tuesday, February 19 Name: NetID: Lab Section (Day/Time): This is a closed book and closed

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 13 Merging using Queue ADT and Queue types In the

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

Lists. ordered lists unordered lists indexed lists 9-3

Lists. ordered lists unordered lists indexed lists 9-3 The List ADT Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations Compare list implementations 9-2 Lists A list is a

More information

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1 CSE 1 Complexity Analysis Program Efficiency [Sections 12.1-12., 12., 12.9] Count number of instructions executed by program on inputs of a given size Express run time as a function of the input size Assume

More information

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS Questions are based on the Main and Savitch review questions for chapter 5 in the Exam Preparation section of the webct course page. In case you haven t observed

More information

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S. Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S. Bowers 1 of 11 Doubly Linked Lists Each node has both a next and a prev pointer head \ v1 v2 v3 \ tail struct

More information

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is

More information

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is

More information

15-122: Principles of Imperative Computation, Spring Due: Thursday, March 10, 2016 by 22:00

15-122: Principles of Imperative Computation, Spring Due: Thursday, March 10, 2016 by 22:00 15-122 Programming 7 Page 1 of 8 15-122: Principles of Imperative Computation, Spring 2016 Programming homework 7: Text Buers Due: Thursday, March 10, 2016 by 22:00 For the programming portion of this

More information

Programming. Lists, Stacks, Queues

Programming. Lists, Stacks, Queues Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation

More information

CMSC 341 Lecture 10 Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees CMSC 341 Lecture 10 Binary Search Trees John Park Based on slides from previous iterations of this course Review: Tree Traversals 2 Traversal Preorder, Inorder, Postorder H X M A K B E N Y L G W UMBC CMSC

More information

4/27/2014. Templates II. Warmup Write the templated Swap function. Class Templates CMSC 202

4/27/2014. Templates II. Warmup Write the templated Swap function. Class Templates CMSC 202 Templates II CMSC 202 Warmup Write the templated Swap function void Swap( T& a, T& b ) T temp = a; a = b; b = temp; Class Templates Fundamental Idea Define classes that operate on various types of objects

More information

Design Patterns in C++

Design Patterns in C++ Design Patterns in C++ Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 15, 2011 G. Lipari (Scuola Superiore Sant Anna) Exception Safety April 15,

More information

CMPT 225. Lecture 6 linked list

CMPT 225. Lecture 6 linked list CMPT 225 Lecture 6 linked list 1 Last Lecture Class documentation Linked lists and its operations 2 Learning Outcomes At the end of this lecture, a student will be able to: define one of the concrete data

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

Object Oriented Software Design - II

Object Oriented Software Design - II Object Oriented Software Design - II Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 12, 2012 G. Lipari (Scuola Superiore Sant Anna) Exception Safety

More information

The time and space are the two measure for efficiency of an algorithm.

The time and space are the two measure for efficiency of an algorithm. There are basically six operations: 5. Sorting: Arranging the elements of list in an order (either ascending or descending). 6. Merging: combining the two list into one list. Algorithm: The time and space

More information

Data Structure (CS301)

Data Structure (CS301) WWW.VUPages.com http://forum.vupages.com WWW.VUTUBE.EDU.PK Largest Online Community of VU Students Virtual University Government of Pakistan Midterm Examination Spring 2003 Data Structure (CS301) StudentID/LoginID

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion. 1. What is the full form of LIFO? The full form of LIFO is Last In First Out. 2. Give some examples for stack application. The examples of stack application are reverse a string, post fix evaluation, infix

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Lecture Notes on Queues

Lecture Notes on Queues Lecture Notes on Queues 15-122: Principles of Imperative Computation Frank Pfenning and Jamie Morgenstern Lecture 9 February 14, 2012 1 Introduction In this lecture we introduce queues as a data structure

More information

Data Structures (INE2011)

Data Structures (INE2011) Data Structures (INE2011) Electronics and Communication Engineering Hanyang University Haewoon Nam Lecture 4 1 Stacks Insertion and deletion are made at one end () Last input first output (LIFO) Inserting

More information

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer. C++ - Lesson 2 1. Explain the following declarations: a) int *a(int a[]); This is a function prototype. 'a' is a function that takes an integer array argument and returns an integer pointer. b) const char

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Introduction to Data Structures and Algorithms

Introduction to Data Structures and Algorithms Introduction to Data Structures and Algorithms Data Structure is a way of collecting and organising data in such a way that we can perform operations on these data in an effective way. Data Structures

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what

More information

Introduction to Linked List: Review. Source:

Introduction to Linked List: Review. Source: Introduction to Linked List: Review Source: http://www.geeksforgeeks.org/data-structures/linked-list/ Linked List Fundamental data structures in C Like arrays, linked list is a linear data structure Unlike

More information

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,

More information

Data Structures Fakhar lodhi Chapter 5: Trees

Data Structures Fakhar lodhi Chapter 5: Trees Chapter 5 Trees Introduction Linked-lists are essentially used to store and organize data where the relationship among data is linear or one-dimensional (a circular structure can be considered as a special

More information

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018 CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node

More information

Arrays and Linked Lists

Arrays and Linked Lists Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every

More information

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19 Data Structures Alice E. Fischer Lecture 4, Fall 2018 Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall 2018 1 / 19 Outline 1 Ordered Lists 2 Sorted Lists Tail Pointers 3 Doubly Linked Lists

More information

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam.

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1 Name: Score Max I. 20 II. 20 III. 20 IV. 40 Instructions: 1. This is a closed-book, closed-notes exam. 2. You have 75 minutes for the exam. 3. Calculators,

More information

Stack and Queue. Stack:

Stack and Queue. Stack: Stack and Queue Stack: Abstract Data Type A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations

More information

Largest Online Community of VU Students

Largest Online Community of VU Students WWW.VUPages.com http://forum.vupages.com WWW.VUTUBE.EDU.PK Largest Online Community of VU Students MIDTERM EXAMINATION SEMESTER FALL 2003 CS301-DATA STRUCTURE Total Marks:86 Duration: 60min Instructions

More information

PROBLEM 1 : (Vocabulary: 8 points) For each of the words/phrases below, circle the denition that is the best description as it pertains in the context

PROBLEM 1 : (Vocabulary: 8 points) For each of the words/phrases below, circle the denition that is the best description as it pertains in the context Test 1: CPS 100 Owen Astrachan February 12, 1996 Name: Honor code acknowledgement (signature) Problem 1 Problem 2 Problem 3 Problem 4 Extra TOTAL: value 8 pts. 18 pts. 13 pts. 16 pts. 6 pts. 57 pts. grade

More information

Sequential Containers Cont'd

Sequential Containers Cont'd Cont'd Carlos Moreno cmoreno @ uwaterloo.ca EIT-4103 https://ece.uwaterloo.ca/~cmoreno/ece250 Today's class: Sequential Containers We'll complete our discussion on sequential containers We'll briefly talk

More information

CS 231 Data Structures and Algorithms Fall DDL & Queue Lecture 20 October 22, Prof. Zadia Codabux

CS 231 Data Structures and Algorithms Fall DDL & Queue Lecture 20 October 22, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 DDL & Queue Lecture 20 October 22, 2018 Prof. Zadia Codabux 1 Agenda Mid Semester Analysis Doubly Linked List Queue 2 Administrative None 3 Doubly Linked

More information

Information Science 2

Information Science 2 Information Science 2 - Basic Data Structures- Week 02 College of Information Science and Engineering Ritsumeikan University Today s class outline l Basic data structures: Definitions and implementation

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms First Semester 2017/2018 Linked Lists Eng. Anis Nazer Linked List ADT Is a list of nodes Each node has: data (can be any thing, int, char, Person, Point, day,...) link to

More information

(Refer Slide Time: 00:02:00)

(Refer Slide Time: 00:02:00) Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 18 Polyfill - Scan Conversion of a Polygon Today we will discuss the concepts

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Introduction to Programming in C Department of Computer Science and Engineering

Introduction to Programming in C Department of Computer Science and Engineering Introduction to Programming in C Department of Computer Science and Engineering Once we know structures and pointers to structures, we can introduce some very important data structure called link list.

More information

Data Structures and Algorithms Notes

Data Structures and Algorithms Notes Data Structures and Algorithms Notes Notes by Winst Course taught by Dr. G. R. Baliga 256-400 ext. 3890 baliga@rowan.edu Course started: September 4, 2012 Last generated: December 18, 2013 Interfaces -

More information

Stacks and Their Applications

Stacks and Their Applications Chapter 5 Stacks and Their Applications We have been discussing general list structures. In practice, we often work with some restricted cases, in which insertions and/or deletions occur only at one or

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Stacks Eng. Anis Nazer First Semester 2017-2018 Stack An Abstract data type (ADT) Accessed only on one end Similar to a stack of dishes you can add/remove on top of stack

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid:

CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid: CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid: CS 2150 Exam 1 Name You MUST write your e-mail ID on EACH page and put your name on the top of this page, too. If you are still writing when pens down

More information

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures Data Structures in C C Programming and Software Tools N.C. State Department of Computer Science Data Structures in C The combination of pointers, structs, and dynamic memory allocation allow for creation

More information

Sequential Containers Cont'd

Sequential Containers Cont'd Cont'd Carlos Moreno cmoreno @ uwaterloo.ca EIT-4103 https://ece.uwaterloo.ca/~cmoreno/ece250 Standard reminder to set phones to silent/vibrate mode, please! Today's class: Sequential Containers We'll

More information

CP2 Revision. theme: dynamic datatypes & data structures

CP2 Revision. theme: dynamic datatypes & data structures CP2 Revision theme: dynamic datatypes & data structures structs can hold any combination of datatypes handled as single entity struct { }; ;

More information

Lecture 9. Pointer, linked node, linked list TDDD86: DALP. Content. Contents Pointer and linked node. 1.1 Introduction. 1.

Lecture 9. Pointer, linked node, linked list TDDD86: DALP. Content. Contents Pointer and linked node. 1.1 Introduction. 1. Lecture 9 Pointer, linked node, linked list TDDD86: DALP Utskriftsversion av Lecture in Data Structures, Algorithms and Programming Paradigms 22nd September 2017 Ahmed Rezine, IDA, Linköping University

More information

CHAPTER 4 LINKED LISTS

CHAPTER 4 LINKED LISTS CHAPTER 4 LINKED LISTS Iris Hui-Ru Jiang Fall 2008 2 Contents Array vs. list Singly linked lists Doubly linked lists Applications Readings Chapter 4 C++ STL list iterators iterator, const_iterator reverse_iterator,

More information

Question Bank Subject: Advanced Data Structures Class: SE Computer

Question Bank Subject: Advanced Data Structures Class: SE Computer Question Bank Subject: Advanced Data Structures Class: SE Computer Question1: Write a non recursive pseudo code for post order traversal of binary tree Answer: Pseudo Code: 1. Push root into Stack_One.

More information

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10 Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()

More information

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 Data Structures Course Review FINAL Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Final When: Wednesday (12/12) 1:00 pm -3:00 pm Where: In Class

More information

Problem with Scanning an Infix Expression

Problem with Scanning an Infix Expression Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix

More information

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items

More information

Lists, Stacks, and Queues

Lists, Stacks, and Queues Data Structure Chapter 4 Lists, Stacks, and Queues Dr. Patrick Chan School of Computer Science and Engineering South China University of Technology Outline Lists (Ch 4.1) Introduction (4.1) Array-based

More information

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 11. Linked Lists. Mark Redekopp 1 CS 103 Unit 11 Linked Lists Mark Redekopp 2 NULL Pointer Just like there was a null character in ASCII = '\0' whose ue was 0 There is a NULL pointer whose ue is 0 NULL is "keyword" you can use in C/C++

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Topic 11 Linked Lists

Topic 11 Linked Lists Topic 11 "All the kids who did great in high school writing pong games in BASIC for their Apple II would get to college, take CompSci 101, a data structures course, and when they hit the pointers business

More information