Top Banner
56

linked list (c#)

Jun 17, 2015

Download

Education

swajahatr

presentation for link lis in c++
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: linked list (c#)
Page 2: linked list (c#)
Page 3: linked list (c#)

List data structure

This is a new data structure. The List data structure is among the most generic

of data structures. In daily life, we use shopping list, groceries list, list of people to invite to a dinner, list of presents to give etc. In this course, we will see how we use lists in programming.

A list is the collection of items of the same type.The items, or elements of the list, are stored in

some particular order.It is possible to insert new elements at various

positions in the list and remove any element of the list.

Page 4: linked list (c#)

List data structure

List is a set of elements in a linear order. Suppose we have four names a1, a2, a3, a4 and their order is as (a3, a1, a2, a4) i.e. a3, is the first element, a1 is the second element, and so on.

The order is important here; this order is either due to sorting, the order may be due to the importance of the data items.

Page 5: linked list (c#)

Operations a programmer performs with a list data structure.

Operation Name Description

createList() Create a new list (presumably empty)

copy() Set one list to be a copy of another

clear(); Clear a list (remove all elements)

insert(X, ?) Insert element X at a particular position in the list

remove(?) Remove element at some position in the list

get(?) Get element at a given position

update(X, ?) Replace the element at a given position with X

find(X) Determine if the element X is in the list

length() Returns the length of the list.

Page 6: linked list (c#)

List Data StructureWe need to know what is meant by “particular position”. There

are two possibilities:  Use the actual index of element: i.e. insert it after element 3, get element

number 6. This approach is used with arrays Use a “current” marker or pointer to refer to a particular position in the list.

The first option is used in the data structures like arrays. When we have to manipulate the arrays, we use index like x[3], x[6].

In the second option we do not use first, second etc for position but say wherever is the current pointer. Just think of a pointer in the list that we can move forward or backward. When we say get, insert or update while using the current pointer, it means that wherever is the current pointer, get data from that position, insert data after that position or update the data at that position. In this case, we need not to use numbers. But it is our responsibility that current pointer is used in a proper way.

Page 7: linked list (c#)

List Data StructureIf we use the “current” marker, the following

four methods would be useful:

Functions Description

start() Moves the “current” pointer to the very first element

tail() Moves the “current” pointer to the very last element

next() Move the current position forward one element

back() Move the current position backward one element

Page 8: linked list (c#)

List ImplementationNow we will see what the implementation of

the list is and how one can create a list.Suppose we want to create a list of integers.

For this purpose, the methods of the list can be implemented with the use of an array inside.

For example, the list of integers A= (2, 6, 8, 7, 1) can be represented in the following manner where the current position is 3.

A 2 6 8 7 1 current size

Index 1 2 3 4 5 3 5

Page 9: linked list (c#)

add Method The add method is used for adding an element to the list. Suppose we want to add a new element in the list i.e. add(9). To add(9) to the list at the current position, at first, we have to make

space for this element. For this purpose, we shift every element on the right of 8 (the current position) to one place on the right. Thus after creating the space for new element at position 4, the array can be represented as

A 2 6 8 7 1 current sizeIndex 1 2 3 4 5 4 5

• Now in the second step, we put the element 9 at the empty space i.e. position 4.

• Thus the array will attain the following shape.

A 2 6 8 9 7 1 current sizeIndex 1 2 3 4 5 6 4 6

Page 10: linked list (c#)

next Method

The next method moves the current position one position forward.

In this method, we do not add a new element to the list but simply move the pointer one element ahead.

There is an array to store the list in it. We also have two variables- current and size to store the position of current pointer and the number of elements in the list.

Page 11: linked list (c#)

remove MethodThe remove method removes the element residing at the current

position. Suppose there are 6 elements (2, 6, 8, 9, 7, 1) in the list. The

current pointer is pointing to the position 5 that has the value 7. We remove the element, making the current position empty. The size of the list will become 5. This is represented in the following figure.

• We fill in the blank position left by the removal of 7 by shifting the values on the right of position 5 to the left by one space. This means that we shift the remaining elements on the right hand side of the current position one place to the left

A 2 6 8 9 1 current sizeIndex 1 2 3 4 5 6 5 6

5

A 2 6 8 9 1 current sizeIndex 1 2 3 4 5 5 5

Page 12: linked list (c#)

find Method find (x) function is used to find a specific element in the array. We pass the element, which is to be found, as an argument to the

find function. This function then traverses the array until the specific element is found.

If the element is found, this function sets the current position to it and returns 1 i.e. true.

On the other hand, if the element is not found, the function returns 0 i.e. false.

Following is the code of this find(x) function in C++.

int find (int x){

int j ;for (j = 1; j < size + 1; j++ )

if (A[j] == x ) break ;

if ( j < size + 1) // x is found{ current = j ; //current points to the position where x found

return 1 ; // return true}return 0 ; //return false, x is not found

Page 13: linked list (c#)

Other Methods There is a get() method , used to get the element from the current

position in the array.   return A[current] ;

Another function is update(x). This method is used to change (set) the value at the current position.

A [current] = x ; Then there is a method length( ).This method returns the size of the

list. return size ;

The back() method decreases the value of variable current by 1. In other words, it moves the current position one element backward.

current -- ; The start() method sets the current position to the first element of the

list. We know that the index of the array starts from 0 but we use the index 1 for the starting position. We do not use the index zero. So we set the current position to the first element by writing.

current = 1 ; Similarly, the end() method sets the current position to the last

element of the list i.e. size. current = size ;

 

Page 14: linked list (c#)

Analysis of Array ListAdd

Worst Case: To add an element at the beginning of the list is the worst case of add method.

Best Case: We have to shift no element if we add at the end.

RemoveWorst Case: To remove an element at the beginning of

the list is the worst case of remove method.Average Case: In average cases of the remove method

we expect to shift half of the elements.Best Case: We have to shift no element if we remove at

the end. Find

Worst Case: The worst case of the find method is that it has to search the entire list from beginning to end.

Average Case: On average the find method searches at most half the list.

Page 15: linked list (c#)
Page 16: linked list (c#)

List using Linked Memory

When we have declared the size of the array, it is not possible to increase or decrease it during the execution of the program. If we need more elements to store in the array, there is need of changing its size in the declaration. We have to compile the program again before executing it.

To avoid such problems, usually faced by the programmers while using an array, there is need of using linked memory in which the various cells of memory, are not located continuously.

In this process, each cell of the memory not only contains the value of the element but also the information where the next element of the list is residing in the memory.

It is not necessary that the next element is at the next location in the memory. It may be anywhere in the memory. We have to keep a track of it.

Page 17: linked list (c#)

For the utilization of the concept of linked memory, we usually define a structure,

called linked list.

Page 18: linked list (c#)

Linked Lists

A linked list, or one-way list is a linear collection of data elements called nodes, where linear order is given by means of pointer.

A linked list is a series of connected nodesEach node contains at least

A piece of data (any type)Pointer to the next node in the list

Head: pointer to the first nodeThe last node points to NULL

A

Head

B C

A

data pointer

node

Page 19: linked list (c#)

Linked List Now let’s consider our previous list, used

with an array i.e. 2, 6, 8, 7, 1. Following is the figure which represents the list stored as a linked list.

We also have a pointer current to point to the current node of the list. We need this pointer to add or remove current node from the list.

In the linked list, the current is a pointer and not an index as we used while using an array.

2

Head

6 178

Current

Page 20: linked list (c#)

Representation of Link List in Computer Memory

Page 21: linked list (c#)

Inserting a new node Possible cases of Insertion

1. Insert into an empty list2. Insert in front3. Insert at back4. Insert in middle

But, in fact, only need to handle two cases Insert as the first node (Case 1 and Case 2) Insert in the middle or at the end of the list

(Case 3 and Case 4)

Page 22: linked list (c#)

Inserting to the Front

1. Allocate a new node2. Insert new element3. Have new node point to old head4. Update head to point to new node

head 48 17 142head 93

Page 23: linked list (c#)

Inserting to the End

1.Allocate a new node2.Insert new element3.Have new node point to null4.Have old last node point to new node5.Update tail to point to new node

48 17 142head //93 //

Page 24: linked list (c#)

Inserting to the Middle

1.Allocate a new node2.Insert new element3.Go to the node that should follow the one

to add4.Have that node point to the new node 5.Have new node point to node next node to

the found node

17 48 142head //93 //142

Page 25: linked list (c#)

Searching a Linked ListSearching refers to finding a particular ITEM

in the data.Binary search algorithm can not be applied to

sorted link list since there is no way indexing the middle element in the list. This property is one of the main drawbacks in using a linked list as a data structure

Page 26: linked list (c#)

Deleting a node

Possible cases of Deletion1. Delete in front2. Delete at back3. Delete in middle

There are two special cases Delete first node Delete the node in middle or at the end of the list

Page 27: linked list (c#)

The Scenario

4 17

head

426

4 17

head

426

4 17

head

42

4 17

head

42

Page 28: linked list (c#)

Traversing a Link List

Traversal means “visiting” or examining each node.

Simple linked listStart at the beginningGo one node at a time until the end

Page 29: linked list (c#)

Link List in C#A linked list is a collection of class

objects called nodes. Each node is linked to its successor

node in the list using a reference to the successor node.

A node is made up of a field for storing data and the field for the node reference.

The reference to another node is called a link.

Page 30: linked list (c#)

AN OBJECT-ORIENTED LINKED LIST DESIGNA linked list will involve at least two classes. We’ll create a Node class and instantiate a

Node object each time we add a node to the list.

The nodes in the list are connected via references to other nodes.

These references are set using methods created in a separate LinkedList class.

Page 31: linked list (c#)

The Node ClassA node is made up of two data members: Element,

which stores the node’s data; and Link, which stores a reference to the next node in the list.

Here’s the code for the Node class:

public class Node {public Object Element;public Node Link;

public Node() {Element = null;Link = null;

}public Node(Object theElement) {

Element = theElement;Link = null;

}}

Page 32: linked list (c#)

The LinkedList ClassThe LinkedList class is used to create the

linkage for the nodes of our linked list. The class includes several methods for adding nodes to the list, removing nodes from the list, traversing the list, and finding a node in the list.

Here’s the code for the LinkedList class:

public class LinkedList {protected Node header;

public LinkedList() {header = new Node();

}. . .}

Page 33: linked list (c#)

Insert Method

private Node Find(Object item) {Node current = new Node();current = header;

while(current.header != item)current = current.Link;return current;

}

public void Insert(Object newItem, Object after) {Node current = new Node();Node newNode = new Node(newItem);current = Find(after);newNode.Link = current.Link;current.Link = newNode;

}

Page 34: linked list (c#)

Remove Methodprivate Node FindPrevious(Object n) {

Node current = header;while(!(current.Link == null) && (current.Link.Element != n))current = current.Link;return current;

}

public void Remove(Object n) {Node p = FindPrevious(n);if (!(p.Link == null))

p.Link = p.Link.Link;}

Page 35: linked list (c#)

PrintList Methodpublic void PrintList() {

Node current = new Node();current = header;

while (!(current.Link == null)) {Console.WriteLine(current.Link.Element);current = current.Link;

}}

Page 36: linked list (c#)

Analysis of Link Listadd and remove

In case of an array, if we have to add an element in the centre of the array, the space for it is created at first. For this, all the elements that are after the current pointer in the array, should be shifted one place to the right.

In Link List we insert a new node after the current node in the chain. For this, we have to change two or three pointers while changing the values of some pointer variables. Its cost, in terms of CPU time or computing time, is not much as compared to the one with the use of arrays.

Page 37: linked list (c#)

Analysis of Link Listfind

The worst-case in find is that we may have to search the entire list. In find, we have to search some particular element say x. If found, the currentNode pointer is moved at that node.

As there is no order in the list, we have to start search from the beginning of the list. We have to check the value of each node and compare it with x (value to be searched).

If found, it returns true and points the currentNode pointer at that node otherwise return false. Suppose that x is not in the list, in this case, we have to search the list from start to end and return false.

If we compare this with array, it will be the same. We don’t know whether x is in the array or not. So we have to search the complete array.

Page 38: linked list (c#)

Variations of Linked ListsDoubly linked lists

Each node points to not only successor but the predecessor

There are two NULL: at the first and last nodes in the list

Advantage: given a node, it is easy to visit its predecessor. Convenient to traverse lists backwards

A

Head

B C

Page 39: linked list (c#)

Variations of Linked ListsCircular linked lists

The last node points to the first node of the list

How do we know when we have finished traversing the list? (Tip: check if the pointer of the current node is equal to the head.)

A

Head

B C

Page 40: linked list (c#)

Josephus ProblemConsider there are 10 persons. They would like to choose a

leader. The way they decide is that all 10 sit in a circle. They start a count with person 1 and go in clockwise direction and skip 3. Person 4 reached is eliminated. The count starts with the fifth and the next person to go is the fourth in count. Eventually, a single person remains.

2

34

5

6

7

8910

N=10, M=34

5

6

7

8

9

10

1

2

3

Eliminated

Page 41: linked list (c#)

Josephus Problem

Suppose if the value of N is 300 or 400 and the value of M is 5 or 10. Now who will be the leader?

This is a mathematical problem where we can change the values of N and M. There is a formula where the values of N, M are allotted. You can calculate who should become the leader.

Here we will solve this with the circular link list. We arrange these numbers in a circularly-linked list, point the head pointer at the starting number and after calling the next method for three times, we will reach the node which is to be removed. We will use the remove method to remove the node. Then the next method is called thrice from there and the node is removed. We will continue this till we have only one node.

Page 42: linked list (c#)

Array versus Linked ListsLinked lists are more complex to code and manage than

arrays, but they have some distinct advantages.Dynamic: a linked list can easily grow and shrink in

size. We don’t need to know how many nodes will be in the list.

They are created in memory as needed. In contrast, the size of a C++ array is fixed at compilation

time.Easy and fast insertions and deletions

To insert or delete an element in an array, we need to copy to temporary variables to make room for new elements or close the gap caused by deleted elements.

With a linked list, no need to move other nodes. Only need to reset some pointers.

Page 43: linked list (c#)

What is a Priority Queues?

Stores prioritized elements No notion of storing at particular position.

Returns elements in priority order Order determined by key.

Page 44: linked list (c#)

What’s so different?Stacks and Queues

Removal order determined by order of inserting

Priority QueueOrder determined by keyKey may be part of element data or separateOrder of returned elements is not FIFO or LIFO

(as in queue or stack)

Page 45: linked list (c#)

Priority QueueIn Priority Queue data elements are

arranged according to priority values and allows the insertion of any order but allows to remove data elements according to their priority values.

Page 46: linked list (c#)

Continue….The highest priority element is always at

the front of the queue and is removed first of all

The highest priority can be either the minimum value of all the items, or the maximum value

We will assume the highest priority is the maximum value

Note that in a priority queue "first in first out" does not apply in general.

Page 47: linked list (c#)

Why Priority Queue ?There are many practical situations

which employ priority queue.

Scheduler for an Operating System

Printer Queue

Sorting• Heap Sort

Page 48: linked list (c#)

The Concept of KeySuppose that you have a few

assignments from different courses. Which assignment will you want to work on first?

Course Priority

Due Date

Database Management System 3 26th-December-2009

Data Structure And Algorithm 1 26th-November-2009

Computer Architecture And Organization

2 6th-December-2009

Page 49: linked list (c#)

Representation of Priority Queue Queue can be represented as

ArrayLinked ListHeap

Page 50: linked list (c#)

One-Way List Representation of a Priority QueueEach node in the list will contain three items

of information: an information field INFO, a priority number PRN and a link number LINK.

A node X precedes a node Y in the list:1. When X has higher priority than Y or2. When both have the same priority but X was

added to the list before Y.

Page 51: linked list (c#)

Array Representation of Priority QueueAnother way to maintain a priority queue in

memory is to use a separate queue for each priority number.

Each such queue will appear in its own circular array and must have its own pair of pointers, FRONT and REAR

If each queue is allocated the same amount of space, a two –dimensional array QUEUE can be used instead of the linear array .

Page 52: linked list (c#)

Linked List based Implementation of Priority Queue

Page 53: linked list (c#)

Continue….

Page 54: linked list (c#)

Implementation of Operation

Page 55: linked list (c#)

Continue….

Page 56: linked list (c#)

Continue….